【问题标题】:jQuery code refactoring of basic toggle functionality基本切换功能的 jQuery 代码重构
【发布时间】:2012-04-12 16:10:45
【问题描述】:

我对 jQuery 很陌生,这是我在 Stack Overflow 上的第一篇文章。

我正在编写一个切换脚本,如果单击了几个(但不是全部)表格单元格,该脚本将切换其下方 tr 的可见性并在其中一个单元格内的 div 上执行更改类显示加号/减号图标。我希望简化我的脚本和 HTML,或者获得有关如何使其变得更好的一般指示。

jQuery如下:

$(function() {

/************************************************************/
// Show/Hide functionality

   $('.showDetails', '#summaryTable').hide();

   $('#summaryTable').on('click', '.toggleIt', function(e){

   var $this = $(this).parents("tr");

   $this.next().toggle(0, function() {
        var rowExpand = $('.rowExpand', $this);
        rowExpand.toggleClass('rowContract');
     });
  });

/************************************************************/

});

HTML如下:

<table id="summaryTable">

<thead>
<tr>
...
</tr>
</thead>

<tbody>

<tr>
<td class="toggleIt"><div class="rowExpand">Expand/Contract details</div></td>
<td class="toggleIt">Content</td>
<td class="toggleIt">Content</td>
<td>*input field*</td>
<td class="toggleIt">Content</td>
<td class="toggleIt">Content</td>
<td>*Trash can icon*</td>
</tr>

<tr class="showDetails">
<td colspan="7" class="expand">

   <div>
     Content to be shown when toggled...
   </div>

</td>
</tr>

<!-- Rinse and repeat -->

</tbody>

</table>

注意到单元格上的所有这些 toggleIt 类,可以单击并让 tr 展开?似乎我应该能够只在我不希望表格在单击时展开的表格单元格上放置一个类。 (输入字段和垃圾桶单元格。)

欢迎任何想法或建议。 谢谢!

【问题讨论】:

  • 这是一个使用 JQuery 的 not() 选择器的 JSFiddle:jsfiddle.net/ypeDw
  • @KarlBarker - 感谢您分享上面的链接。我看到您如何更改我的代码以执行我的要求。查看 jQuery API,并使用 Mikey 的示例,我还能够使用 .not() 方法完成此操作。再次感谢您的帮助!

标签: jquery refactoring toggle


【解决方案1】:

您可以使用 :not 选择器 (http://api.jquery.com/not-selector/) 来执行此操作 例如

$("td:not(.toggleDisabled)").each(function(){$(this).click(function(){$(this).toggle()})})

【讨论】:

  • 太棒了。正是我所希望的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多