当单击子元素以反映当前选择了哪个子元素时,我需要一些添加/删除父元素类的方法。在这种情况下,标签方案中的 UL 父项和 LI 子项。我需要一种方法来标记 UL 上的当前选项卡,以便我可以在 UL 上设置背景精灵的样式;因为在这种情况下,我的 LI 背景样式不适用于图形。
我是 jQuery/Javascript/DOM 新手,但能够为初学者拼凑出一个丑陋的解决方案,
HTML
<!-- tabs -->
<ul class="tabs currenttab-info">
<li id="tab-info" class="info"><strong><a href="#">Information</a></strong></li>
<li id="tab-write" class="write"><strong><a href="#">Write Feedback</a></strong></li>
<li id="tab-read" class="read"><strong><a href="#">Read Feedback</a></strong></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
Javascript
// send '.currenttab-x' to '.tabs' and remove '.currenttab-y' + '.currenttab-z'
// when LI #tab-X is clicked ...
$( '#tab-info' ).click(function() {
// ... find the UL and remove the first possible conflicting class
$('.tabs').removeClass("currenttab-read");
// ... find the UL and remove the other possible conflicting class
$('.tabs').removeClass("currenttab-write");
// ... find the UL and add the class for this LI
$('.tabs').addClass("currenttab-info");
});
// ... repeat ...
$( '#tab-write' ).click(function() {
$('.tabs').removeClass("currenttab-info");
$('.tabs').removeClass("currenttab-read");
$('.tabs').addClass("currenttab-write");
});
$( '#tab-read' ).click(function() {
$('.tabs').removeClass("currenttab-info");
$('.tabs').removeClass("currenttab-write");
$('.tabs').addClass("currenttab-read");
});
Run Code Online (Sandbox Code Playgroud)
这实际上似乎是工作,但它是一个摸索的解决方案,我肯定有一个更好的办法。你们中的一些 jQuery 忍者会知道如何将这个功能非常优雅地组合在一起,有什么帮助吗?
此外,我想添加到这一点,以便点击的 LI 也被赋予一个类来显示它被选中,而其他 LI 被剥离任何此类类。我已经在为 UL 做同样的事情;我可以用我笨拙的方法看到如何做到这一点,但这将意味着越来越多的混乱代码行。如果您的改进还包括更改 LI 类的方法,我将不胜感激
仅供参考:我正在使用 jQuery 工具选项卡,所以我展示了更多的 jQuery,但只有我引用的那一点似乎相关。
如果您不将其用于其他目的,我将删除ids li。
<ul class="tabs currenttab-info">
<li class="info"><strong><a href="#">Information</a></strong></li>
<li class="write"><strong><a href="#">Write Feedback</a></strong></li>
<li class="read"><strong><a href="#">Read Feedback</a></strong></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
$('.tabs li').click(function() {
var $li = $(this);
$li.addClass('current').siblings().removeClass('current'); // adds a current class to the clicked li
var $ul = $li.parent();
$ul.removeClass("currenttab-info currenttab-read currenttab-write")
.addClass("currenttab-" + this.class ); // assuming li only holds one class e.g. class="write"
});
Run Code Online (Sandbox Code Playgroud)