[英]bind event handlers to dynamically created elements via recursion
我想創建一個可編輯的表,以便如果最后一行的所有單元格都有內容,則會自動添加新行。 對於新行中的單元格,應綁定相同的事件處理程序。 這是我的代碼,這是怎么了?
$(document).ready(function(){
$("td").keyup(function(){keyupper($(this))});
});
function keyupper(cell){
// mark all changed cells by yellow
$(cell).css("background-color","rgb(255,255,150)");
/* if all cells in last row are filled, add new row
*/
$("tbody tr:last-child").each(function (){
//$this is the last row
var td0 = $(this).children().eq(0).text();
var td1 = $(this).children().eq(1).text();
var td2 = $(this).children().eq(2).text();
var td3 = $(this).children().eq(3).text();
var td4 = $(this).children().eq(4).text();
//if all fields are filled
if(td0!="" && td1!="" && td2!="" && td3!="" && td4!=""){
//parent of this is tbody
$(this).parent().append("<tr><td contenteditable></td>"
+"<td contenteditable></td>"
+"<td contenteditable></td>"
+"<td contenteditable></td>"
+"<td contenteditable></td></tr>");
$(addedcells) = $(this).parent().children().last().children();
/// list of the cells added in the last row
/// binding the event handler function via recursion
$(addedcells).eq(0).bind("keyup",function(){
keyupper($(addedcells).eq(0));});
$(addedcells).eq(1).bind("keyup",function(){
keyupper($(addedcells).eq(1));});
$(addedcells).eq(2).bind("keyup",function(){
keyupper($(addedcells).eq(2));});
$(addedcells).eq(3).bind("keyup",function(){
keyupper($(addedcells).eq(3));});
$(addedcells).eq(4).bind("keyup",function(){
keyupper($(addedcells).eq(4));});
}
});
}
您是否嘗試在“ keyupper”函數的末尾添加以下語句?
$("td").keyup(function(){keyupper($(this))});
我嘗試了jQuery on()函數,它解決了這個問題。 它允許為尚未創建的元素分配事件處理程序。
例如
$("tbody").on("keyup","td",function(){
keyupper($(this))
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.