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

牧云@^-^@ 提交于 2019-12-12 04:04:23

问题


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>

回答1:


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.




回答2:


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.



回答3:


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.




回答4:


Try use :nth-child()

for (var i = 1; i < 6; i++) {
    $(".foo:nth-child("+i+")").hover(
            function ()
            {
                $(this).fadeIn();
            }, function ()
            {
                $(this).fadeOut();
            });
    }


来源:https://stackoverflow.com/questions/10259213/jquery-select-class-with-a-number-e-g-foo1-foo2-foo3-foo4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!