Javascript 如何查找单击的按钮:jquery
摘要:我有一个html页面,由两个添加按钮和两个表组成。单击“添加”按钮时,行将附加到相应的表中。我在一个html模板中包含了两个具有两个不同父ID的模板。我需要以这样的方式编写脚本:当单击addbtn having parentid==“#a”时,将parentid==“#a”的行追加到表中 result.htmlJavascript 如何查找单击的按钮:jquery,javascript,jquery,Javascript,Jquery,摘要:我有一个html页面,由两个添加按钮和两个表组成。单击“添加”按钮时,行将附加到相应的表中。我在一个html模板中包含了两个具有两个不同父ID的模板。我需要以这样的方式编写脚本:当单击addbtn having parentid==“#a”时,将parentid==“#a”的行追加到表中 result.html //i am using django web framework <div class="reports"> {% include 'temp
//i am using django web framework
<div class="reports">
{% include 'template1.html' with id="a" %}
{% include 'template2.html' with id="b" %}
</div>
//我正在使用django web框架
{%include'template1.html',id=“a”%}
{%include'template2.html',id=“b”%}
每个模板共享/扩展一个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>'
);
$('.reports')。在('click','a.add','b.add',函数(e){
//如何在这里区分两个表。
$(this).find('configuration-table').children('tbody'))
.附加(
''+
''+
''+层\文本+''+
映射元素+
''+单位\文本+''+
''+数据集\u文本+''+
''+
''
);
问题:当我单击“添加”按钮时,该行将附加到两个表中。我不希望这样。我希望将行添加到相应的表中。我希望在同一个函数中执行此操作
我在寻找我在这里缺少的逻辑
提前感谢首先,根据标记,添加按钮和表之间没有父子关系。不过,有很多方法可以解决此问题。下面建议1个选项 假设您有两个带有class
add
的按钮和一个包含表id的数据属性(数据id)
i、 e.具有数据id=“a”的第一个按钮和具有数据id=“b”的第二个按钮,其中a和b是各自表格的id
现在将您的js更新为以下内容
.on('click','.add', function(e) {
var table_id = $(this).data("id");
$("#"+table_id).children('tbody').append..... // your code
}
您的代码正在使用查找按钮的子级。它不是子级,而是按钮的父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);
A太好了!
.on(
连接到什么?您在查找中查找的是元素而不是类。不确定该代码将如何工作,因为该表不是按钮的子项。@epascarello我在这里查找逻辑。请避免指出代码中的愚蠢错误。我的要求是理解概念。无论如何,我已经编辑了它。愚蠢的错误mak很难理解发生了什么。有时“愚蠢”的错误是人们的代码无法工作的原因。记住,我们正试图帮助你。感谢逻辑。我将尝试使用数据ID。谢谢你,它只做了一些小改动。