我正在使用一个名为Jquery Content Panel Switcher的Jquery插件。它完全符合标题所说的内容,它可以轻松切换div。页面的html是:
<!--The switcher buttons, basic anchor tags, with the switcher class -->
<a id="content1" class="switcher">One</a>
<a id="content2" class="switcher">Two</a>
<!-- The panel you wish to use to display the content -->
<div id="switcher-panel"></div>
<!-- The actual content you want to switch in and out of the panel, this is hidden -->
<div id="content1-content" class="switcher-content show"></div>
<div id="content2-content" class="switcher-content show"></div>
在我的每个内容面板中,我都有一个表单。每种形式都有一张表:
<table class="table table-hover" data-controller="rank">
<thead>
<tr>
<th colspan="4" align="left"><h2>Rank 1</h2></th>
</tr>
<tr>
<th>Number</th>
<th>Requirements</th>
</tr>
</thead>
<tbody>
<tr data-name="one_li">
<td>1</td>
<td>Info</td>
</tr>
<tr data-name="two_li">
<td>2</td>
<td>More Info</td>
</td>
</tr>
</tbody>
</table>
如果点击一行,我试图触发一个动作。这是我正在使用的JavaScript:
$(document).ready(function(){
$('#switcher-panel form table tbody tr').click(function(){
console.log("Clicked");
});
});
当我在Chrome控制台中使用$('#switcher-panel form table tbody tr')
的Jquery选择器时,它会找到该表,一切看起来都很好。当我把它放在我的javascript文件中时,没有任何反应。一些方向会很棒。谢谢您的帮助。
答案 0 :(得分:10)
这将有效:
$('#switcher-panel').on('click', 'table tr', function() {
console.log("Clicked", this);
});
如果点击的子项属于#switcher-panel
选择器,则会向click
添加一个监听器,该监听器会监听其子项上的'table tr'
个事件。
Check out this artice了解有关事件委派的更多信息。 (事件委派的Ctrl + f)
答案 1 :(得分:2)
如果动态追加面板的内容,则需要将click事件委托给静态父元素。试试这个:
$('#switcher-panel').on('click', 'form table tbody tr', function(){
console.log("Clicked");
});
我的猜测是你可以将子选择器缩短到table tr
。