我想知道是否有人知道我如何重写这个简单的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:40:30
如果您可以在当前具有image1、image2等的div上放置一类图像,那么您可以这样做:
$(".image").hover(function() {
$(".default").toggle();
$("#cats p").eq($(this).index()).toggle();
}); 这假设图像div的顺序与#cat中的p标记的顺序相同。
http://jsfiddle.net/QVS9X/44/
使用数据属性的示例:
JS:
$(".image").hover(function() {
$(".default").toggle();
$($(this).data('id')).toggle()
}); HTML:
<div class="image" data-id="#cat1">
<p>Hover for cat 1</p>
</div>
<div id="cats">
<p id="cat1">Category 1 text</p>
</div>http://jsfiddle.net/QVS9X/55/
发布于 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
发布于 2011-09-28 20:41:23
以http://jsfiddle.net/QVS9X/45/为例
<div class="image" data-id="1">
<p>Hover for cat 1</p>
</div>
<div class="image" data-id="2">
<p>Hover for cat 2</p>
</div>
<div class="image" data-id="3">
<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>
$(document).ready(function() {
$(".image").mouseout(function() {
$(".default").show();
$(".cat"+$(this).data('id')).hide();
}).mouseover(function() {
$(".default").hide();
$(".cat"+$(this).data('id')).show();
});
});https://stackoverflow.com/questions/7583263
复制相似问题