单击页面上的某个位置以删除类

时间:2015-08-12 21:19:30

标签: jquery

我有一组按钮,点击后会向所有与该按钮无关的div添加一个淡入淡出类。当您单击页面上的任何其他位置时,我需要删除该类。我试过这个,但它没有用。

 $("document").click(function() {
 $( ".project-category-pennsylvania,.project-category-texas,.project-category-florida,.project-category-georgia,.project-category-louisiana,.project-category-delaware" ).removeClass( "fade" );
});

而且我确信有一种更简洁的方式来编写下面的代码,任何有关如何做的建议或信息都将受到赞赏。

以下是代码:

jQuery(function ($) {

$( ".texas" ).click(function() {
$( ".project-category-texas" ).removeClass( "fade" );
$( ".project-category-florida,.project-category-georgia,.project-category-louisiana,.project-category-delaware,.project-category-pennsylvania" ).addClass( "fade" );
});

$( ".florida" ).click(function() {
$( ".project-category-florida" ).removeClass( "fade" );
$( ".project-category-texas,.project-category-georgia,.project-category-louisiana,.project-category-delaware,.project-category-pennsylvania" ).addClass( "fade" );
});

$( ".georgia" ).click(function() {
$( ".project-category-georgia" ).removeClass( "fade" );
$( ".project-category-texas,.project-category-florida,.project-category-louisiana,.project-category-delaware,.project-category-pennsylvania" ).addClass( "fade" );
});

$( ".louisiana" ).click(function() {
$( ".project-category-louisiana" ).removeClass( "fade" );
$( ".project-category-texas,.project-category-florida,.project-category-georgia,.project-category-delaware,.project-category-pennsylvania" ).addClass( "fade" );
});

$( ".delaware" ).click(function() {
$( ".project-category-delaware" ).removeClass( "fade" );
$( ".project-category-texas,.project-category-florida,.project-category-georgia,.project-category-louisiana,.project-category-pennsylvania" ).addClass( "fade" );
});

$( ".pennsylvania" ).click(function() {
$( ".project-category-pennsylvania" ).removeClass( "fade" );
$( ".project-category-texas,.project-category-florida,.project-category-georgia,.project-category-louisiana,.project-category-delaware" ).addClass( "fade" );
});

$("document").click(function() {
$( ".project-category-pennsylvania,.project-category-texas,.project-category- florida,.project-category-georgia,.project-category-louisiana,.project-category-delaware" ).removeClass( "fade" );
});

});

JSFiddle Here

2 个答案:

答案 0 :(得分:1)

document是一个对象,取消引用它!

$(document).click(function() {
 $( ".project-category-pennsylvania,.project-category-texas,.project-category-florida,.project-category-georgia,.project-category-louisiana,.project-category-delaware" ).removeClass( "fade" );
});

答案 1 :(得分:0)

我在你的JsFiddle上测试你添加了这个处理程序

$("[class^='project-category']*").click(function(){
            $(".project-category-texas,.project-category-florida,.project-category-georgia,.project-category-louisiana,.project-category-delaware,.project-category-pennsylvania").removeClass("fade");
});

http://jsfiddle.net/84ov956w/3/