开发者

Jquery mouseenter question

I am a beginner with jquery. I have n divs which if i hover above them another div will fadein. Like this:

    $(".res2").mouseenter(function () {
        $("#jucInfores2").fadeIn("normal");
    });
    $(".res3").mouseenter(function () {
      开发者_JS百科  $("#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");
    });

Is there another way to do this for me not to repeat so many times the code? If i have 20 such divs for example?


I'd suggest you invert the logic and match the #jucInfo elements instead, then use the variable part of their ids to build the class selectors:

$("[id^='jucInfo']").each(function() {
    var $info = $(this);
    $("." + this.id.substr(7)).mouseenter(function() {
        $info.fadeIn("normal");
    });
});


One way is to wrap the main code in a Javascript function (very literal example for readability):

function jucInfo(res, infores) {
    $(res).mouseenter(function () {
        $(infores).fadeIn("normal");
    });
}

to which you can pass all your variables when you call the function:

jucInfo(".res2", "#jucInfores2");
jucInfo(".res3", "#jucInfores3");
...

To refine this further, place all your selector classes and ID pairs in a hash, then make a loop that repeats the above the required number of times (i.e. the number of elements in the hash).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜