0

I try to get the id of li in listview by using following code

$("#detailr").append(" <li class=\"item box_btn\" id=\""+ item.appid +"\"><div class=\"list\" ><div class=\"list-left\"><img src=\"uploadb/"+ item.appicon +"\"><ul><li><b>"+ item.appname +"</b><span>Left"+ item.leftc +"</span></li><li><img src=\"img/32.png\">Done"+ item.appdone +"</li><li class=\"spe\">search\""+ item.appname +"\"</li></ul></div><div class=\"list-right\"><div class=\"yuan\">+"+ item.appprice +"</div></div></div></li>");});

and click events

<script type="text/javascript">
 $(document).ready(function(){ 
   $('#detailr').children('li').click(function () { // 
   alert($(this).attr('id'));
 });
});
</script>

the html content

<ul data-role="listview" id="detailr">
</ul>

when I click the li, there no response, and I change $('#detailr').children('li').click(function () to $('#detailr li').click(function () , $('#detailr').children('li').on("click", function (), also doesn't work, I don't understand why, please help me, many thanks.

spotcool
  • 19
  • 3
  • 1
    `$(document).ready(function () { $('#detailr').click('click', 'li', function () { // alert($(this).attr('id')); }); });` – Arun P Johny May 15 '15 at 04:47
  • 1
    If `#detailr` contents are being created dynamically (after the DOM), then `.click` will not find the element. You will need `selector.on('click", "li", function() { // code });` – Cory May 15 '15 at 04:48
  • @Cory thank you, but it seems a bug with this, the alert will show twice, he first time has no value(shows undefined), the second time will show the id. – spotcool May 15 '15 at 04:56

1 Answers1

1

You need to use .on() and event delegation like so.

$('#detailr').on('click','li',function () { 
    alert($(this).attr('id'));

});
Norlihazmey Ghazali
  • 8,762
  • 1
  • 19
  • 37