如何查找被单击的按钮:jquery

How to find which button is clicked: jquery

本文关键字:单击 按钮 jquery 何查找 查找      更新时间:2023-09-26

总结:我有一个html页面,其中包括两个添加按钮和两个表。单击add按钮时,将向各自的表添加行。我已经包括两个模板与两个不同的父id到一个html模板。我需要以这样的方式编写脚本,即当add-btn具有parentid =="#a"被单击时,将行追加到具有parentid =="#a"的表。

result.html

//i am using django web framework
<div class="reports">        
    {% include 'template1.html' with id="a" %}
    {% include 'template2.html' with id="b" %}
</div>

每个模板共享/扩展一个base.html模板,其中编写所有通用代码

<div class="panel">
    <div>
    <button type="button" class="add btn btn-primary" data-toggle="tooltip" title="Add to configuration list.">
                        <i class="fa fa-plus"></i>
                        Add
                    </button>
                </div>
            <div class ="configuration-table panel-body">
                <table class="table table-striped table-bordered table-condensed">
                    <thead>
                        <tr>
                            <th>Remove</th>
                            <th>Layer</th>
                            <th>Display</th>
                            <th>Unit</th>
                            <th>Dataset</th>
                            <th>Ordering</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
</div>
我的jquery代码是

result.js

    $('.reports').on('click','#a .add, #b .add', function(e) {
//how to differentiate two tables here.
    $(this).find('configuration-table table').children('tbody')
                    .append(
                        '<tr>'+
                        '<td class="remove-row" role="button" aria-label="Remove Region"><i class="fa fa-times" title="Remove this row." data-toggle="tooltip" data-placement="right" aria-hidden="true"></i></td>'+
                        '<td>'+layer_text+'</td>'+
                        map_elements+
                        '<td>'+unit_text+'</td>'+
                        '<td>'+dataset_text+'</td>'+
                        '<td class="ordering" aria-label="Re-order"><i class="fa fa-arrows" title="Re-arrange row order." data-toggle="tooltip" data-placement="right"></i></td>'+
                        '</tr>'
                    );

Issue:当我单击add按钮时,行被附加到两个表中。我不希望那样。我想添加行到各自的表。我想在相同的函数中做到这一点

我正在寻找我在这里缺失的逻辑。

Thanks in advance

您的代码正在使用find查找按钮的子节点。它不是子元素,而是按钮父元素div的兄弟元素。

$(this)  //button that was clicked
   .parent() //div around the button
     .sibling(".configuration-table")  //sibling element that has the table
       .find("table tbody")  //the table
         .append(tableRow);

首先,根据标记,add按钮和表之间没有父子关系。不过,有很多方法可以解决这个问题。

下面建议1个选项

假设您有两个按钮,类为add,数据属性(data-id)包含表的id。

。第一个按钮data-id="a",第二个按钮data-id="b",其中a和b是各自表的id。

现在更新你的js到以下

.on('click','.add', function(e) {
     var table_id = $(this).data("id");
     $("#"+table_id).children('tbody').append..... // your code
}