我想知道是否有人知道如何重写这个简单的 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>
最佳答案
如果你可以将一类图像放在当前有 image1、image2 等的 div 上,那么你可以这样做:
$(".image").hover(function() {
$(".default").toggle();
$("#cats p").eq($(this).index()).toggle();
});
这假设图像 div 的顺序与 #cats 中的 p 标签的顺序相同。
使用数据属性的例子:
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>
关于javascript - 制作更智能的 jQuery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7583263/