Javascript 我们如何获得特定的动态添加的td';函数上jquery中的s id

Javascript 我们如何获得特定的动态添加的td';函数上jquery中的s id,javascript,jquery,Javascript,Jquery,例如,我有如下动态内容 <table> <tr> <td id='id_1' class='myclass'>1</td> <td id='id_2' class='myclass'>2</td> <td id='id_3' class='myclass'>3</td> 现在,当我点击td时,我得到了一些整数,比如说671,而不是td的ID 请告诉我正确的方法,以及上面的代码

例如,我有如下动态内容

<table>
<tr>
    <td id='id_1' class='myclass'>1</td>
    <td id='id_2' class='myclass'>2</td>
    <td id='id_3' class='myclass'>3</td>
现在,当我点击td时,我得到了一些整数,比如说671,而不是td的ID

请告诉我正确的方法,以及上面的代码有什么问题,我不相信$(body)是有效的语法。试试$(document),它似乎可以正常工作:

尝试使用$('body')而不是$(body)

尝试以下操作

$('body td').click(function() {
    console.log($(this).attr('id'));        
});

我已经检查了您的代码,除了上面提到的主体问题外,它似乎工作得很好,因此您的问题必须与动态添加项的方式或您正在使用的jQuery版本有关

下面是用于动态添加项的代码,与您的代码非常类似。我将所选项目输出到一个div,以便它更可见

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
    $(document).ready(function () {
      var counter = 1;
      window.setInterval(function() {
        $('tr').append("<td id='id_"+counter+"' class='myclass'>"+counter+"</td>");
        counter++;
      }, 3000);
      $('body').on('click','.myclass', function() {
        $('#selectedtd').html($(this).attr('id'));  
      });
    });
</script>
</head>
<body>
  <div id="selectedtd"></div>
  <table>
  <tr>
  </tr>
  </table>
</body>
</html>

$(文档).ready(函数(){
var计数器=1;
setInterval(函数(){
$('tr')。追加(“+计数器+”);
计数器++;
}, 3000);
$('body')。在('click','myclass',function()上{
$('#selectedtd').html($(this.attr('id'));
});
});

您使用的是标记选择器$(body),因此它应该用单引号或双引号括起来。否则就随它去吧-

$(document).on('click','.myclass', function() {
    alert($(this).attr('id'));        
});

你认为
671
是什么?动态创建的元素ID是如何生成的?@Reigel我想我是通过Ajax在PHP中生成的BodyID,我用firebug检查了ID是否按预期设置
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
    $(document).ready(function () {
      var counter = 1;
      window.setInterval(function() {
        $('tr').append("<td id='id_"+counter+"' class='myclass'>"+counter+"</td>");
        counter++;
      }, 3000);
      $('body').on('click','.myclass', function() {
        $('#selectedtd').html($(this).attr('id'));  
      });
    });
</script>
</head>
<body>
  <div id="selectedtd"></div>
  <table>
  <tr>
  </tr>
  </table>
</body>
</html>
$(document).on('click','.myclass', function() {
    alert($(this).attr('id'));        
});