gpt4 book ai didi

javascript - Jquery:处理动态添加的行上的点击

转载 作者:行者123 更新时间:2023-11-28 15:20:12 25 4
gpt4 key购买 nike

我使用以下函数向表中添加一行:

function loadTable()
{
var index, html, tbody;
//clear the table

for (index = 0; index < content.length; index++)
{
var tbody = document.getElementById("tablei").getElementsByTagName('tbody')[0];
var row = document.createElement("TR");
row.setAttribute("id", index);
row.setAttribute("class", "selectableRow editableDiv");
var td1 = document.createElement("TD");
td1.innerHTML = content[index].Author;
var td2 = document.createElement("TD");
td2.innerHTML = content[index].AuthorType;
var td3 = document.createElement("TD");
td3.innerHTML = content[index].CosignStatus;
var td4 = document.createElement("TD");
td4.innerHTML = content[index].FileTime;
var td5 = document.createElement("TD");
td5.innerHTML = content[index].NoteTime;

row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
tbody.appendChild(row);
}
}

我添加了一个 jquery 函数来捕获该行上的点击事件。

$('.selectableRow').click(function (event)
{

var id = $(this).attr('id');
var item = content[parseInt(id)];
alert(id);
}

但是单击该行时不会显示任何警报。

但是当我直接在 html 中添加相同的代码时,会调用警报。

最佳答案

那是因为您正在向尚不存在的事物添加处理程序。尝试将您的点击处理程序包装在 change() 函数中:

$(document).change(function(){
$('.selectableRow').click(function (event){
var id = $(this).attr('id');
var item = content[parseInt(id)];
alert(id);
})
});

更好的是,你可以这样做:

$(document).on('click', '.selectableRow', function() {
var id = $(this).attr('id');
var item = content[parseInt(id)];
alert(id);
});

来自 JQuery on()

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

关于javascript - Jquery:处理动态添加的行上的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com