2013-03-23 22 views
1

比如我有動態內容如下我們如何獲得特定動態添加TD的ID 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> 

.... 和我的功能是

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

現在當我點擊td時,我得到一些整數讓我們說671而不是我的td的ID。

請建議我這樣做的正確的方式,什麼是錯誤的與上面的代碼

+0

你覺得'671'是什麼? – Reigel 2013-03-23 07:32:32

+0

如何生成動態創建的元素ID? – pdoherty926 2013-03-23 07:33:49

+0

@Reigel我認爲身體的ID – 2013-03-23 07:36:14

回答

1

嘗試使用$( '主體'),而不是$(身體)

1

我不相信$(體)是有效的語法。嘗試的$(document)代替,它似乎只是很好地工作:jsfiddle working

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

嘗試以下

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

我已經檢查過你的代碼,除了上面提到的正文問題,它似乎工作的很好,所以你的問題必須與你動態添加項目的方式或者你正在使用的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> 
0

您正在使用標籤選擇器$(body),所以它應該被包含在單引號或雙引號中。否則一起去吧 -

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