如何在动态生成的表行jquery中添加和操作id

时间:2015-12-02 07:08:06

标签: javascript jquery html

我遇到了如何为我的行添加标识符的问题。 我有这个代码使用json数据填充表体。

var table = '';
$.each(result, function (i, item) {
    table += '<tr class="test"><td>' + item.ip_address + '</td><td>' + item.app_name + '</td><td>' + item.crit_severity + '</td><td>' + item.user_password + '</td></tr>';
});
$("#tableLinks tbody").html(table); 

我有这张桌子

<table class="table table-bordered" id="tableLinks" style="width:70%;margin">
  <thead>
    <tr>
      <th>IP ADDRESS</th>
      <th>APPLICATION NAME</th>
      <th>CRIT/SEVERITY</th>
      <th>USERNAME/PASSWORD</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

我使用此代码进行测试,但它不起作用。这可能是什么错误?感谢

$(".test").on('click', function() {
   alert('test');
});

1 个答案:

答案 0 :(得分:7)

目前您使用的是“直接”绑定,它只会在您的代码进行事件绑定调用时附加到页面上存在的元素。

在动态生成元素或操作选择器(如删除和添加类)时,需要使用Event Delegation委托事件方法.on()

一般语法

$(staticParentSelector).on('event','selector',callback_function)

实施例

$("#tableLinks tbody").on('click', ".test", function(){
    alert('test');
});

代替document,您应该使用最近的静态容器。

  

委派事件的优点是,它们可以处理来自稍后添加到文档的后代元素的事件。通过选择在附加委托事件处理程序时保证存在的元素,我们可以使用委托事件将click事件绑定到动态创建的元素,并且还避免频繁附加和删除事件处理程序的需要。

$(function() {

  $("#tableLinks tbody").on('click', ".test", function() {
    snippet.log('test');
  });

 var result = [{
   ip_address : 123456,
   app_name:'test',
   crit_severity: 'crit_severity',
   user_password: 'user_password'
   }];
  var table = '';
  $.each(result, function(i, item) {
    table += '<tr class="test"><td>' + item.ip_address + '</td><td>' + item.app_name + '</td><td>' + item.crit_severity + '</td><td>' + item.user_password + '</td></tr>';
  });
  $("#tableLinks tbody").html(table);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<table class="table table-bordered" id="tableLinks" style="width:70%;margin">
  <thead>
    <tr>
      <th>IP ADDRESS</th>
      <th>APPLICATION NAME</th>
      <th>CRIT/SEVERITY</th>
      <th>USERNAME/PASSWORD</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

相关问题