我是jquery的初学者。 我有 n 个 div,如果我将鼠标悬停在它们上方,另一个 div 就会淡出。 像这样:
$(".res2").mouseenter(function () {
$("#jucInfores2").fadeIn("normal");
});
$(".res3").mouseenter(function () {
$("#jucInfores3").fadeIn("normal");
});
$(".res4").mouseenter(function () {
$("#jucInfores4").fadeIn("normal");
});
$(".res5").mouseenter(function () {
$("#jucInfores5").fadeIn("normal");
});
$(".res6").mouseenter(function () {
$("#jucInfores6").fadeIn("normal");
});
$(".res7").mouseenter(function () {
$("#jucInfores7").fadeIn("normal");
});
$(".scl").mouseenter(function () {
$("#jucInfoscl").fadeIn("normal");
});
$(".scc").mouseenter(function () {
$("#jucInfoscc").fadeIn("normal");
});
$(".scr").mouseenter(function () {
$("#jucInfoscr").fadeIn("normal");
});
$(".ml").mouseenter(function () {
$("#jucInfoml").fadeIn("normal");
});
$(".mcl").mouseenter(function () {
$("#jucInfomcl").fadeIn("normal");
});
有没有另一种方法可以让我不重复代码这么多次? 例如,如果我有 20 个这样的 div?
最佳答案
我建议您反转逻辑并匹配 #jucInfo
元素,然后使用其 id 的变量部分来构建类选择器:
$("[id^='jucInfo']").each(function() {
var $info = $(this);
$("." + this.id.substr(7)).mouseenter(function() {
$info.fadeIn("normal");
});
});
关于jquery鼠标输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7063930/