Bootstrap选项卡更改父背景Jquery
我试图找出一个更优雅的解决方案。 但到目前为止,我的jquery技能有限。
我想有一种更好的方法来实现下面的function。 用几句话说。 我试图在点击时更改父级的背景。
现在,我只是添加一个类,并从其他按钮中删除其他可能的类。
相关HTML:
Ebenfalls lesenswert
相关CSS:
.bpp-toggled { background: orange !important; } .blp-toggled { background: lime !important; } .bpc-toggled { background: purple !important; }
jQuery的
$("#btn-popular-posts").click(function() { $('.widget-latest-posts').addClass('bpp-toggled'); $('.widget-latest-posts').removeClass('blp-toggled'); $('.widget-latest-posts').removeClass('bpc-toggled'); }); $("#btn-latest-posts").click(function() { $('.widget-latest-posts').addClass('blp-toggled'); $('.widget-latest-posts').removeClass('bpp-toggled'); $('.widget-latest-posts').removeClass('bpc-toggled'); }); $("#btn-popular-comments").click(function() { $('.widget-latest-posts').addClass('bpc-toggled'); $('.widget-latest-posts').removeClass('blp-toggled'); $('.widget-latest-posts').removeClass('bpp-toggled'); });
你能帮助我一个更好的更优雅的解决方案,或者我可以做一些研究的关键词。 因为现在,由于我会添加更多按钮,因此很难维护。
谢谢您的帮助!
编辑:我知道toggleClass。 但那种情况并没有成功。 因为它只是在第二次点击时删除了该类。
这只是使用数据属性来保持按钮本身的类。 您还可以使用带有正则表达式的removeClass中的函数来删除初始切换类,然后再应用新类。
在将来添加按钮时,您只需要确保按钮具有正确的data-target-class属性以及在css中设置的正确类。 只要遵循一致的命名约定,就不需要对javascript进行任何更改。
$("button[data-toggle='tab']").click(function() { $('.widget-latest-posts').removeClass(function (index, className) { return (className.match (/([az]{3,3})-toggled/g) || []).join(' '); } ); $('.widget-latest-posts').addClass($(this).attr("data-toggled-class")); });
.bpp-toggled { background: orange !important; } .blp-toggled { background: lime !important; } .bpc-toggled { background: purple !important; }
Ebenfalls lesenswert