Michal
Michal

Reputation: 3368

jQuery click function for <ul><li> elements

I have a unordered list looking like this:

<ul id="frozen" data-name="nameOfSelect" class="tagit">
   <li class="tagit-choice" tagvalue="2" style="padding-right: 4px;" id="tag-2">
      <div class="tagit-label" data-value="2">kázeň</div>
   </li>
   <li class="tagit-choice" tagvalue="1" style="padding-right: 4px;" id="tag-1">
      <div class="tagit-label" data-value="1">žalmxxxx</div>
   </li>
</ul>

I need to bind an click function to all of them and get the data of the id="tag-1" to be used in the function.

I have tried this:

$('#[id|="tag"]').each(function(){
    var tag = this.attr('id'); 
    var tagID = tag.replace('tag-',''); 
    this.click(function (){
       alert('index.php?s=taglist&tag=' + tagID);
       //window.location = string;
    });
});

However, for some reason it seems that this approach is wrong for the <li> element as I am having problems with the selector (it seems). Maybe I am also missing something stupid... Any ideas?

Upvotes: 1

Views: 293

Answers (1)

adeneo
adeneo

Reputation: 318342

No need for a loop, jQuery does this internally, and this is a native DOM element, which has an id property, but no attr() method :

$('[id^="tag-"]').on('click', function() {
    var tag = this.id,
        tagID = tag.replace('tag-', '');

    alert('index.php?s=taglist&tag=' + tagID);
});

Upvotes: 5

Related Questions