1.我运行这些代码。
<table id="widgetTable" class="table table-hover">
<thead>
<tr>
<th>NO.</th>
</tr></thead> </table>
//skip details
$("#widgetTable > tbody:last").append('<tr><td>'+ (i+1) +'</td></tr>);
//upper code line is succeesed in run time
- 但使用浏览器的调试工具时,在表中找不到追加td(源代码不变(
- 所以底层代码没有被激活?我该怎么办!告诉我一个方法…:(
$( document ).ready(function() {
$('#widetTable').find('tr').click( function(){
var selected = $(this).hasClass("highlight");
$("#widetTable tr").removeClass("highlight");
if(!selected)
$(this).addClass("highlight");
alert('You clicked row '+ ($(this).index()+1) );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
您似乎想在动态添加tr的表的tr元素上附加一个点击事件。如果是…,那么试试这个
$( document ).ready(function() {
$('#widetTable').on("click", "tr", function(event){
var selected = $(this).hasClass("highlight");
$("#widetTable tr").removeClass("highlight");
if(!selected)
$(this).addClass("highlight");
alert('You clicked row '+ ($(this).index()+1) );
});
});
对于动态生成的元素,您希望使用.on()
方法。所以这个:
$('#widetTable').find('tr').click( function(){
将变成:
$('#widetTable').on( 'click', 'tr', function() {
更多详情点击此处
我更喜欢.on而不是.click,因为前者可以使用更少的内存,并且可以用于动态添加的元素。