7

我正在使用一个名为 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 控制台中使用 Jquery 选择器时$('#switcher-panel form table tbody tr'),它会找到表格并且一切看起来都很好。当我把它放在我的 javascript 文件中时,什么也没有发生。一些方向会很棒。谢谢您的帮助。

4

2 回答 2

12

这将起作用:

$('#switcher-panel').on('click', 'table tr', function() {
    console.log("Clicked", this);
});

例子

如果单击的子项位于选择器之下,则这会向其添加一个侦听器来#switcher-panel侦听其子项上的事件。click'table tr'

查看这篇文章以获取有关事件委托的更多信息。(Ctrl+f 用于事件委托)

于 2012-11-22T14:37:07.337 回答
3

如果面板的内容是动态附加的,您需要将点击事件委托给静态父元素。尝试这个:

$('#switcher-panel').on('click', 'form table tbody tr', function(){
    console.log("Clicked");
});

我的猜测是您也可以将子选择器缩短table tr为。

于 2012-11-22T14:35:59.120 回答