2014-09-29 71 views
0

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), 
      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> 

我怎么能修改此所以,如果没有项目选中一个新的CSS类将应用于所有项目。如果有任何事情被点击,这个类应该被删除。

回答

0
if (selector.length == 0) 
    // add class to all items 

只需在它之前创建.join()或$(selector).length(如果连接完成)。

2

,如果你有一个或多个$(selector)您可以测试:

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'); 
} 
+0

这增加了MyClass的正确,但是当我再选择其他项目,以使选择长度不再0它不会删除MyClass的,并保持它在 – fightstarr20 2014-09-30 00:14:57

+0

好吧,看我的编辑 – Brewal 2014-09-30 01:07:31

相关问题