1

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

$("#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");       
        }); 
4

4 回答 4

2
$('#Auckland,#Northland,#Rodney').hover(function(){
     $('.'+this.id).addClass("area");
},function(){
     $('.'+this.id).removeClass("area");
});
于 2012-07-15T21:35:56.340 回答
2

请尝试将它们链接在一起:)

明显的好处是您编写的代码更少。编写和管理更轻松、更快捷。但是您的代码也运行得更快。查看没有链接的第一个片段。每一行都告诉 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/

于 2012-07-15T21:37:22.833 回答
2

您可以为所有元素添加一个类cities并尝试以下操作:

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

$(".cities").mouseout(function(){                                                
     $("." + this.id).removeClass("area");        
}); 
于 2012-07-15T21:37:51.460 回答
1

我想这可以写成...

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

您(或某人)可能很想用 just 重写它toggleClass,但这是一个错误的举动,请参阅:如果有人刷新页面并将鼠标悬停在一个目标项目上,则悬停会搞砸。) 我想,这应该可以正常工作。

于 2012-07-15T21:35:38.200 回答