2012-07-15 72 views
1

我想清理这个jQuery代码,有什么建议吗?我有大约20个城市要添加。此代码在地图上滚动区域时向每个城市添加CSS类。我想清理这个jQuery代码,有什么建议吗?

$("#Auckland").mouseover(function(){             
       $(".Auckland").addClass("area");   
     }); 

     $("#Auckland").mouseout(function(){            
       $(".Auckland").removeClass("area");  
     }); 

     $("#Northland").mouseover(function(){            
       $(".Northland").addClass("area");  
     }); 

     $("#Northland").mouseout(function(){             
       $(".Northland").removeClass("area");   
     }); 

     $("#Rodney").mouseover(function(){            
       $(".Rodney").addClass("area");  
     }); 

     $("#Rodney").mouseout(function(){            
       $(".Rodney").removeClass("area");  
     }); 
+0

而不是安装如此多的事件监听器,你应该将一个事件侦听器附加到父元素,然后进行筛选。查看'.on()' – xbonez 2012-07-15 21:34:59

回答

2
$('#Auckland,#Northland,#Rodney').hover(function(){ 
    $('.'+this.id).addClass("area"); 
},function(){ 
    $('.'+this.id).removeClass("area"); 
}); 
1

我想这可以写成一样......

$('#Auckland, #Northland, #Rodney').hover(function() { 
    var targetClass = this.id; 
    $('.' + targetClass).addClass('area'); 
}, function() { 
    var targetClass = this.id; 
    $('.' + targetClass).removeClass('area'); 
}); 

您(或其他人)可能会受到诱惑,只需toggleClass改写这一点,但它是一个假动作,请参阅:如果有人刷新一个页面,将鼠标悬停在目标物品上方,盘旋就会变得臃肿。 )我想这应该是正确的。

2

PLZ试试这个链接在一起:)

明显的好处是你写更少的代码。编写和管理起来更简单快捷。但是你的代码也运行得更快。看看第一个没有链接的片段。每一行都告诉jQuery首先搜索整个DOM以获取对象,然后在该对象上运行一个方法。当我们使用链接时,jQuery只需要一次搜索对象。

$("#Auckland,#Northland,#Rodney").mouseover(function() { 
    $(this).addClass("area"); // you can do - > $("." + this.id) if you want to add calss to all the emelents with taht class 
    // you can do - > you can also change it with the class name depending your needs 
}); 

$("#Auckland,#Northland,#Rodney").mouseout(function() { 
    $(this).removeClass("area"); 
}); 

好读:http://tobiasahlin.com/blog/quick-guide-chaining-in-jquery/

& http://www.jquery-tutorial.net/introduction/method-chaining/

+1

+1的文档,好建议bro':)'。 – undefined 2012-07-15 21:47:55

+1

@Raminson':)'我刚刚意识到你是未定义的:)谢谢 – 2012-07-15 21:49:36

2

你可以像cities添加一个类的所有元素,并尝试这个办法:

$(".cities").mouseover(function(){             
    $("." + this.id).addClass("area");   
}); 

$(".cities").mouseout(function(){             
    $("." + this.id).removeClass("area");   
});