jQuery select class with a number. e.g. foo1, foo2

2019-09-18 14:05发布

I am trying to select a list of divs (foo#) and fadeIn another div (zxcv#) on hover. I assigned a var in javascript but the end effect is only showing in foo6?

<div class="foo1"><div class="zxcv1"></div></div>
<div class="foo2"><div class="zxcv2"></div></div>
<div class="foo3"><div class="zxcv3"></div></div>
<div class="foo4"><div class="zxcv4"></div></div>
<div class="foo5"><div class="zxcv5"></div></div>
<div class="foo6"><div class="zxcv6"></div></div>

<script type="text/javascript">
        for (var i = 1; i < 6; i++) {
        $(".foo"+i).hover(
                function ()
                {
                    $(".zxcv"+i).fadeIn();
                }, function ()
                {
                    $(".zxcv"+i).fadeOut();
                });
        }
</script>

4条回答
手持菜刀,她持情操
2楼-- · 2019-09-18 14:10

You could use an "attribute starts with" selector:

$("div[class^='foo']").hover(function() {
    $(this).find("div[class^='zxcv']").fadeIn();
}, function() {
    $(this).find("div[class^='zxcv']").fadeOut();
});

That removes the need for a loop, since most jQuery methods apply to every element in the set.

查看更多
冷血范
3楼-- · 2019-09-18 14:29

Try use :nth-child()

for (var i = 1; i < 6; i++) {
    $(".foo:nth-child("+i+")").hover(
            function ()
            {
                $(this).fadeIn();
            }, function ()
            {
                $(this).fadeOut();
            });
    }
查看更多
冷血范
4楼-- · 2019-09-18 14:34

You can select all with $("[class^='foo']") (also see here):

$("[class^='foo']").hover(
    function () {
        $(this).find("[class^='zxcv']").fadeIn();
    }, function () {
        $(this).find("[class^='zxcv']").fadeOut();
    }
);

Also see my example.

查看更多
▲ chillily
5楼-- · 2019-09-18 14:35

You are closing over the loop variable i in your callbacks, which has the end result that i is always 6 inside them (you can check this out with console.log or alert).

To solve the problem you need to make sure that each of your callbacks gets its own value of i. Since Javascript variables are not scoped to blocks but to whole functions, this means that you need to call a function with the current value of i each time:

for (var i = 1; i < 6; i++) {
    (function(i) {
        $(".foo"+i).hover(
                function ()
                {
                    $(".zxcv"+i).fadeIn();
                }, function ()
                {
                    $(".zxcv"+i).fadeOut();
                });
    })(i);
}

A couple of notes:

  • The loop condition is i < 6 instead of i <= 6 -- is this a bug?
  • As others have already said, in this specific case you can avoid the closure problem entirely by using a different selector.
查看更多
登录 后发表回答