javascript源代码在附加了表的td、tr之后发生了什么

what happend in javascript source after appended td,tr of table

本文关键字:td tr 之后 什么 发生了 源代码 javascript      更新时间:2023-09-26

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
  1. 但使用浏览器的调试工具时,在表中找不到追加td(源代码不变(
  2. 所以底层代码没有被激活?我该怎么办!告诉我一个方法…:(

$( 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,因为前者可以使用更少的内存,并且可以用于动态添加的元素。