2016-12-03 132 views
0

我有一个通过JavaScript基于SQL查询中的数据动态生成的表格。第一个单元格包含一个按钮,该按钮应检索该行onclick中的第二个单元格中的值。出于某种原因,jQuery onclick事件不会触发。浏览器中没有错误发生。从动态生成表格中的单元格获取值

HTML

... 
for (var i=0; i<queryReturned.Result.length; i++) { 
    var tableRow = document.createElement("tr"); 
    var cell = document.createElement("td"); 
    var button = document.createElement("button"); //Button gets added here 
    button.type = "button"; 
    button.value = "Remove Alert"; 
    button.className = "buttonSelect" 
    cell.appendChild(button); 
    tableRow.appendChild(cell); 
    //This loop creates the rest of the cells and fills in their data 
    for (var j=0; j<Object.keys(queryReturned.Result[i]).length; j++) { 
    var cell2 = document.createElement("td"); 
    var cellText = document.createTextNode(Object.values(queryReturned.Result[i])[j]); 
    cell2.appendChild(cellText); 
    tableRow.appendChild(cell2); 
    } 
    tableBody.appendChild(tableRow); 
} 
table.appendChild(tableBody); 
table.setAttribute("border", "2"); 
body.appendChild(table); 
... 

jQuery的

$(document).ready(function(){ 
$(".buttonSelect").on('click',function(){ 
    var currentRow=$(this).closest("tr"); 
    var col2=currentRow.find("td:eq(1)").html(); 
    alert(col2); //alert for now to test if we grabbed the data 
    }); 
}); 
+0

改写你的事件处理函数,如下所示:'$(document).on('click','.buttonSelect',function(){...});'动态添加元素。 (我不是100%确定'$(this)'是否与你的版本相同。) – connexo

+0

Thanks @connexo。那就是诀窍。你应该完全补充说,作为答案,我可以给你应有的信用! –

回答

1

改口事件处理函数,像这样:

$(document).on('click', '.buttonSelect', function(){ ... }); 

所以它会动态地添加的元素正常工作。

让我们知道它是怎么回事!

1

首先,主要问题是您需要使用委托事件处理程序将click事件附加到button元素。

此外,你正在使用JS和jQuery的奇怪混合。您可以大量简化表创建逻辑。太。试试这个吧:

$(function() { 
    var $table = $('<table />').appendTo('body'); // this wasn't in your code example, but should look like this 

    queryReturned.Result.forEach(function(result) { 
    var $tr = $("<tr />").appendTo($table); 
    var $td = $("<td />").appendTo($tr);  
    $('<button class="buttonSelect">Remove Alert</button>').appendTo($td); 

    for (var j = 0; j < Object.keys(result).length; j++) { 
     $('<td />').text(result[j]).appendTo($tr); 
    } 
    } 

    $(document).on('click', '.buttonSelect', function() { 
    var currentRow = $(this).closest("tr"); 
    var col2 = currentRow.find("td:eq(1)").html(); 
    alert(col2); 
    }); 
}); 
+0

这非常有用。是的,我是一个初学者,所以我一直在拼凑一切。感谢您的伟大建议! –