私は、SQLクエリからのデータに基づいてJavaScript経由で動的に生成されるテーブルを持っています。最初のセルには、その行内の2番目のセルの値をクリックする必要があるボタンが含まれています。何らかの理由で、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
});
});
「$(document).on( 'click'、 '.buttonSelect'、function(){...}); 'のようにイベントハンドラ関数を書き換えてください。動的に追加された要素も同様です。 (私は$(これ)があなたのバージョンと同じになるかどうかは100%確信していません) – connexo
ありがとう@connexo。それがトリックでした。それを完全に答えとして追加して、私はあなたに正当な信用を与えることができます! –