Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery wildcard selector on attributes

I have this stuff

<table>
  <tr>
    <td>
      foo
    </td>
    <td>
      <a href="#" data-action:edit="1">[EDIT]</a>
      <a href="#" data-action:delete="1">[DEL]</a>
    </td>
  </tr>
  <tr>
    <td>
      bar
    </td>
    <td>
      <a href="#" data-action:edit="2">[EDIT]</a>
      <a href="#" data-action:delete="2">[DEL]</a>
    </td>
  </tr>
  <tr>
    <td>
      foobar
    </td>
    <td>
      <a href="#" data-action:edit="3">[EDIT]</a>
      <a href="#" data-action:delete="3">[DEL]</a>
    </td>
  </tr>
</table>

And I was able to get individual attributes by this selectors:

$('[data-action\\:edit]') or $('[data-action\\:delete]')

How can I get all data-action:* elements?

like image 913
Ragen Dazs Avatar asked Jan 22 '26 22:01

Ragen Dazs


1 Answers

Here is an alternative solution using KnockoutJS instead of jQuery for doing this sort of thing (Binding actions to elements).

Instead of storing the data in the DOM we'll be storing it in JavaScript objects.

I know this is not exactly what you were looking for, but I think it provides a cleaner solution to the underlying problem.

HTML:

<table>
    <tbody data-bind="foreach: elements">
        <tr>
            <td data-bind="text: name"></td>
            <td> 
                <a href="#" data-bind="click: $root.edit">[EDIT]</a>
                <a href="#" data-bind="click: $root.del">[DEL]</a>
            </td>
        </tr>
    </tbody>
</table>

JavaScript:

function tElement(name){
    this.name = name;
}

function ViewModel(arr){
    var self=this;
    this.elements = ko.observableArray(arr);
    this.del = function(elem){
        self.elements.remove(elem);
    }
    this.edit = function(elem){
        alert("edit called on element with name "+elem.name);    
    }
}

var vm = new ViewModel([new tElement("foo"),new tElement("bar"),new tElement("foobar")]);

ko.applyBindings(vm);

Working JSFiddle

like image 151
Benjamin Gruenbaum Avatar answered Jan 24 '26 14:01

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!