簡體   English   中英

從動態生成的表中的單元中獲取價值

[英]Getting value from cell within dynamically generated table

我有一個表,該表是根據SQL查詢中的數據通過JavaScript動態生成的。 第一個單元格包含一個按鈕,該按鈕應在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
  });
});

重新編寫事件處理函數,如下所示:

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

因此它也適用於動態添加的元素。

讓我們知道怎么回事!

首先,主要問題是您需要使用委托事件處理程序將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);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM