2017-06-01 22 views
-1
var table = $("<table />").attr({id:'table1'});    
     var appenddata; 
     names = Object.keys(res); 
     var row = $('<tr />'); 
     $(names).each(function (index, value) { 
      $(row).append("<th>" + value + "</th>"); 
     }); 
     $(table).append(row); 
     $(Result).each(function (index, value) { 
      var tr = $('<tr />').attr({}); 
      $(names).each(function (i,iValue) { 
       $(tr).append("<td>" + value[names[i]]+"</td>"); 
      }); 
      $(table).append(tr); 
     }); 

     $("#tab1").append(table); 

enter image description here如何在表格的行添加事件处理

enter image description here 我有这个表,我想在行添加click事件,就像如果用户点击该行的任何地方,它显示一个警告。

+0

的[添加一个onclick事件到表行]可能的复制(https://stackoverflow.com/questions/1207939/adding-an-的onclick事件到一个表行) –

回答

1

只需使用on()点击即可动态创建元素。添加下面的代码在你的js

$(document).on('click','#table1 tr',function(){ 
alert('something') 
}) 
0

这应该工作:

// table is a refence to the HTMLTableElement 
var trList = table.getElementsByTagName("tr"); 
for(var index = 0; index < trList.length; index++) { 
    trList[index].addEventListener("click", function(event) { 
     alert("Row Clicked"); 
    }); 
} 

这里是一个工作示例

var table = document.getElementById("table"); 
 
var trList = table.getElementsByTagName("tr"); 
 
for(var index = 0; index < trList.length; index++) { 
 
    (function (index){ 
 
     trList[index].addEventListener("click", function(event) { 
 
      alert("Row " + (index+1) + " Clicked"); 
 
     }); 
 
    }(index)); 
 
}
<table id="table"> 
 
    <tbody> 
 
    <tr> 
 
     <td> 
 
     Row 1 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     Row 2 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

0

你不能带A事件未来的元素! 您必须使用其他元素来为将来的元素代理事件!

$("body").on('click','#table1 tr',function(){ 
    alert('your msg'); 
}) 
0

你可以做这样的事情:

 $(function(){ 
     $(document).on('click','#table1 tr',function(e){ 
      alert(this.data('message')); 
     }) 
     }); 


     // This will come inside your custom method or ajax success 
     var table = $("<table />").attr({id:'table1'});    
     var appenddata; 
     names = Object.keys(res); 
     var row = $('<tr />'); 
     $(names).each(function (index, value) { 
      $(row).append("<th>" + value + "</th>"); 
     }); 
     $(table).append(row); 
     $(Result).each(function (index, value) { 

      var tr = $('<tr />', { 'class': 'classname','data-message' :value[names[i]]}); 
      $(names).each(function (i,iValue) { 
       $(tr).append("<td>" + value[names[i]]+"</td>"); 
      }); 
      $(table).append(tr); 
     }); 

     $("#tab1").append(table); 
相关问题