我想知道是否有人知道我如何重写这个简单的jquery代码以提高效率。当然,它现在运行得很好,但我想象添加10个以上的项目会使代码变得非常大。我想也许我可以将类添加到数组中,并使用某种循环?不过,我不确定这是不是正确的方法。
这里是jsfiddle:http://jsfiddle.net/QVS9X/42/
下面是一个示例: JS:
$(".image1").mouseout(function() {
$(".default").show();
$(".cat1").hide();
}).mouseover(function() {
$(".default").hide();
$(".cat1").show();
});
$(".image2").mouseout(function() {
$(".default").show();
$(".cat2").hide();
}).mouseover(function() {
$(".default").hide();
$(".cat2").show();
});HTML:
<div class="image1 image">
<p>Hover for cat 1</p>
</div>
<div class="image2 image">
<p>Hover for cat 2</p>
</div>
<div class="image3 image">
<p>Hover for cat 3</p>
</div>
<div class="default">
<p>Default Text</p>
</div>
<div id="cats">
<p class="cat1">Category 1 text</p>
<p class="cat2">Category 2 text</p>
<p class="cat3">Category 3 text</p>
</div>发布于 2011-09-28 20:38:55
var myDefault = $(".default");
var myCat1 = $(".cat1");
var myCat2 = $(".cat2");然后
$(".image1").mouseout(function() {
myDefault.show();
myCat1.hide();
}).mouseover(function() {
myDefault .hide();
myCat1 .show();
});
$(".image2").mouseout(function() {
myDefault.show();
myCat2.hide();
}).mouseover(function() {
myDefault.hide();
myCat2.show();
});将减少dom遍历,并且improve performance
https://stackoverflow.com/questions/7583263
复制相似问题