jQuery在未选择任何内容时添加类
我有一个jQuery脚本,它根据单击的项目选择(突出显示)和取消选择divjQuery在未选择任何内容时添加类,jquery,Jquery,我有一个jQuery脚本,它根据单击的项目选择(突出显示)和取消选择div <script> jQuery(document).ready(function($) { $links = $('.property'); $links.click(function(e) { //Get our variables, simply $(this) and the colour var $this = $(this),
<script>
jQuery(document).ready(function($) {
$links = $('.property');
$links.click(function(e) {
//Get our variables, simply $(this) and the colour
var $this = $(this),
color = $this.data('col');
//Toggle the active class on this link
$this.toggleClass('active');
//Remove .main on all .test's
$(".slayout").removeClass("main");
$(".product").addClass("trans");
$(".product").removeClass("main");
//Map the active link's data-col with a dot attributes to an array
//Join it up to make a selector
var selector = $links.filter('.active').map(function(){
return "."+$(this).data('col');
}).get().join('');
//Add the class back on to matches
$(selector).addClass('main');
//Finally, prevent the default action
e.preventDefault();
});
});
</script>
jQuery(文档).ready(函数($){
$links=$('.property');
$links。单击(函数(e){
//获取我们的变量,只需$(这个)和颜色
变量$this=$(this),
color=$this.data('col');
//切换此链接上的活动类
$this.toggleClass('active');
//移除所有的主管道。测试
$(.slayout”).removeClass(“主”);
$(“.product”).addClass(“trans”);
$(“.product”).removeClass(“主”);
//使用点属性将活动链接的数据列映射到数组
//把它连接起来,组成一个选择器
变量选择器=$links.filter('.active').map(函数(){
返回“+$(this).data('col');
}).get().join(“”);
//将类重新添加到匹配项中
$(选择器).addClass('main');
//最后,防止默认操作
e、 预防默认值();
});
});
我如何修改它,以便在没有选择任何项目的情况下,将新的CSS类应用于所有项目。如果单击了任何内容,则应删除此类
if (selector.length == 0)
// add class to all items
只要不要在它前面加上.join(),如果连接完成,就不要加上$(选择器).length。您可以测试是否有一个或多个<代码>$(选择器):
var selector = $links.filter('.active').map(function(){
return "."+$(this).data('col');
}).get().join('');
// remove the class added when there was no item selected
$('.allitems').removeClass('myclass');
if ($(selector).length > 0) {
//Add the class back on to matches
$(selector).addClass('main');
} else {
$('.allitems').addClass('myclass');
}
这将正确地添加myclass,但当我选择另一个项目,使选择器长度不再为0时,它不会删除myclass并将其保留