如何在表行上添加事件处理程序

时间:2017-06-01 08:59:50

标签: javascript jquery html asp.net-mvc c#-4.0

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事件,就像用户点击行上的任何地方一样,它会显示警告。

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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");
    });
}

这是一个工作示例

&#13;
&#13;
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));
}
&#13;
<table id="table">
  <tbody>
    <tr>
      <td>
        Row 1
      </td>
    </tr>
    <tr>
      <td>
        Row 2
      </td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您无法将活动加入未来元素! 您必须使用其他元素来代理未来元素的事件!

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

答案 3 :(得分: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);
相关问题