jQuery实现点击切换表格<th>显示隐藏(ExpressionEngine环境)
Hey there! Since you're new to jQuery, let's break down what's going wrong and get this toggle working cleanly—no extra fluff required.
First, let's spot the issue with your original code:
$('.plus', '.minus').click(function() { $(this).toggle(); $(this).next().toggle(); });
The selector $('.plus', '.minus') doesn't target both elements like you think it does. The second argument in jQuery is a context (where to look for the first selector), not a second selector. To target both .plus and .minus, you need to use a comma-separated selector: $('.plus, .minus').
Also, using .next() can be fragile if ExpressionEngine adds extra markup between your <th> elements later. Instead, use .siblings() to safely target the other toggle button, regardless of extra structure.
Solution 1: Clean Toggle with Siblings
This approach works even if EE adds extra classes/markup around your <th> elements:
<th class="plus">+</th> <th class="minus">-</th>
/* Start with one button hidden */ .minus { display: none; }
$('.plus, .minus').click(function() { // Toggle the clicked button $(this).toggle(); // Toggle the other button (its sibling) $(this).siblings('.plus, .minus').toggle(); });
Solution 2: Even More Concise
If you just need to flip the visibility of both buttons every time either is clicked, you can simplify further—no need to target siblings individually:
$('.plus, .minus').click(function() { $('.plus, .minus').toggle(); });
Since one starts hidden and the other visible, toggling both will always flip their states perfectly.
Quick Troubleshooting Tips
- Make sure jQuery is loaded: In ExpressionEE's control panel, sometimes jQuery is loaded in noConflict mode. If your code doesn't work, try replacing
$withjQuery:jQuery('.plus, .minus').click(function() { jQuery('.plus, .minus').toggle(); }); - Verify selectors work: Open your browser's dev tools (F12), go to the Console tab, and run
$('.plus, .minus')—it should return both elements. If not, adjust your selector to be more specific (e.g.,$('th.plus, th.minus')to target only<th>elements with those classes).
That's it! These solutions avoid repetition, work around EE's automatic markup changes, and keep your code nice and clean.
内容的提问来源于stack exchange,提问作者user6818018

