如何选择动态生成的特定li元素

时间:2015-08-20 06:33:02

标签: javascript jquery html

我无法在点击中选择一个动态生成的特定li元素。请帮忙。

Jquery的

$(document).ready(function() 
 {
$('#id1').on('click', 'li', function(e) 
{ 
 var val = $(this).find('.pick').attr('data-val1');
 console.log(val); // returns only first value for every click
 });
 });

动态创建HTML

 var x = document.getElementById("id1");
x.innerHTML= x.innerHTML + '<li class="pick" data-val1="'+i+'"></li>' // where i is a incremental counter

HTML

<ul id ="id1">
 // li adds here
</ul>

2 个答案:

答案 0 :(得分:0)

尝试

&#13;
&#13;
$(document).ready(function() {
  $('#id1').on('click', 'li', function(e) {
    var val = $(this).attr('data-val1');
    snippet.log('clciekd: ' + val); // returns only first value for every click
  });

  var i = 0;
  $('button').click(function() {
    $('<li />', {
      'data-val1': ++i,
      text: i
    }).appendTo('#id1');
  })
});
&#13;
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="id1"></ul>
<button>Add</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试此解决方案:http://jsfiddle.net/nec47v8d/

您可以使用此 JQUERY

$('#id1 li.pick').click(function (e) {
    var val = $(this).attr('data-val1');
    alert(val)
});