gpt4 book ai didi

javascript - 将事件动态绑定(bind)到表行和列

转载 作者:行者123 更新时间:2023-11-30 08:39:51 25 4
gpt4 key购买 nike

我试图仅在第二列应用点击事件并在第三列的按钮上应用点击事件,但事件未触发。

html:

<table class="table table-bordered table-hover">
<tr>
<td class="webIcon">
<img src="Img/icon.png"></img>
</td>
<td class="tabTitle tabRow">Smith</td>
<td class="closeTab">
<button type="button" class="btn btn-default btn-sm " aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</td>
</tr>
</table>

j查询:

 $( '.table tr:nth-child(2)').delegate("td","click",function(){
$('.tabRow').click(function(){
var id = $(this).parents('tr').attr('id');
console.log(id);
});
});

$( '.table tr:nth-child(3)').delegate("td","click",function(){
$('.button').click(function(){
var id = $(this).parents('tr').attr('id');
console.log(id);
});
});

最佳答案

您的代码更复杂。试试这个

$( '.table .tabTitle').on("click",function(){            
var id = $(this).parents('tr').attr('id');
console.log(id);
});

$( '.table .btn').on("click",function(){
var id = $(this).parents('tr').attr('id');
console.log(id);
});

$('.table .tabTitle').on("click", function() {

var id = $(this).parents('tr').attr('id');
console.log(id);

});

$('.table .btn').on("click", function() {

var id = $(this).parents('tr').attr('id');
console.log(id);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table table-bordered table-hover">
<tr id="ID1">
<td class="webIcon">
<img src="Img/icon.png"></img>
</td>
<td class="tabTitle tabRow">Smith</td>
<td class="closeTab">
<button class="btn btn-default btn-sm " aria-label="Left Align">Button
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</td>
</tr>
</table>

编辑:

  • 尽可能避免使用 nth-child(n) 选择器,因为这会影响页面的加载性能。

关于javascript - 将事件动态绑定(bind)到表行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com