将事件侦听器添加到动态表的每一行?

时间:2018-12-28 00:21:03

标签: javascript jquery html bootstrap-4

我有一个要使用JSON文件填充的表。 JSON条目的数量(因此表行)可以是任意长度。每行都包含一个引导程序下拉按钮,该按钮具有用于重命名或删除表行之类的链接。

我已经尝试了几种在网上找到的解决方案,其中大多数包括foreach循环,但是在尝试将这些实现到我的代码中时遇到了很多问题。

function populate()
{
    $.getJSON(, {})
    .done(function(data) {
        $.each(data, function(i, items) 
        {
            table.append(
                `<tr>
                     <td>
                         <div class="btn-group dropdown">
                             <button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                 Actions
                             </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="#" onclick="renameEntry()">Rename</a>
                            </div>
                        </div>
                    </td>
                </tr>`
            )
        });
    });
}    

如您所见,我尝试使用onclick()方法来触发js函数,但是我不知道如何最好地区分行,因此onclick()仅影响相关行

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

  

使用onclick()方法触发js函数

通常因为您将演示文稿与逻辑混为一谈而感到厌烦。使得调试变得困难。

如果您要向DOM中动态添加任何内容,并希望针对这些动态元素发生click事件,则JQuery提供了一种以它们为目标的方法,而不会冒泡事件处理程序的性能,也不会在添加元素时对监听器进行任何动态添加。 / p>

您可以使用.on()方法来定位容器中的元素。

$(document).ready(() => {
  $('.js-add-row').on('click', () => {
    $('.js-dyn-table').append('<tr><td>New Row <button class="js-hello">Hello</button> </td></tr>')
  });
  
  // Target the first container that has dynamic elements,
  // in this case the table
  // the second selector is the element that we want the event to occur on: .js-hello
  $('.js-dyn-table').on('click', '.js-hello', (e) => {
    // e.currentTarget is the element the event occured on
    var $btn = $(e.currentTarget);
    // closest will work it's way up parent html elements until it finds the first match
    var $tr = $btn.closest('tr');
    
    $tr.toggleClass('bg-yellow');
  });
});
table{
  border: 1px solid green; 
  margin-top: 10px
}

.bg-yellow {
  background-color: Gold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="js-add-row" type="button" value="Add Row">

<table class="js-dyn-table">
  <tr><td>Existing Row<button class="js-hello">Hello</button> </td></tr>
</table>

答案 1 :(得分:0)

在这种情况下,您只需要一个元素this,该元素将允许您访问已单击的DOM元素,您将回到e的级别(可以给任何名称)。 我不知道您打算如何使用此信息,但是在我的示例中,我解释了如何访问被单击的DOM元素。

请看下面的代码,希望对您有所帮助。

function test(e) {
  e.style.background = "red";
}
<div onclick="test(this)">
    <button>Click me</button>
</div>

相关问题