Вопрос

I have the following list:

<ol class="sortable ui-sortable">
    <li id="list_1608"><div>One</div></li>
    <li id="list_1609"><div>Two</div></li>
    <li id="list_1610"><div>Three</div></li>
</ol>

I want to get the id of any li that is clicked. I have tried the following code but get no alert.

$("li").click(function() {
    var myid = $(this).attr("id");
    alert(myid);
});

I am using this in conjunction with the nestedSortable jQuery Plugin.

Where am I going wrong?

Ok Further info, the list items are added after the dom is loaded.

If the items are loaded to start with it does work, apologies.

Это было полезно?

Решение

Your code is working here, you may need to put it in document.ready() or need to add jQuery files. Using this.id instead of $(this).attr("id") is better option here as it is javascript and gives you performance benefit.

$(document).ready(function(){

     $("li").click(function() {
        //var myid = $(this).attr("id");
        alert(this.id);
     });

})

Другие советы

You can get the id with:

this.id

This might help.

$('ol').click(function(event){
if(event.target.tagName == 'li'){alert(this.id);}
if($(event.target).parent('li').length > 0){$(this).parent().attr('id');}
});

Check whether you have loaded the jquery library properly first within head tag

<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
     $("li").click(function() {
        var myid = $(this).attr("id");
        alert(myid);
     });
});
</script>

Just for future reference. Although the above answer was correct for static data I forgot to mention that the elements were added after the DOM had loaded. The solution was in fact..

$("li").live("click", function({
    alert(this.id);
 });
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top