jQuery "for" loop

jQuery "for" loop

本文关键字:quot loop for jQuery      更新时间:2023-09-26

我想在这里写一些非常基本的jQuery代码。

我在这里做的是我想让图像在悬停时切换。我有5张图片,当我编写5个代码时,我能够存档,每个图像1个。

        $('#menu > ul:first-child > li:nth-child(1)').hover(function(){
            $('li:nth-child(1) > .image-hover').toggle();
            $('li:nth-child(1) > .image').toggle();
        });
        $('#menu > ul:first-child > li:nth-child(2)').hover(function(){
            $('li:nth-child(2) > .image-hover').toggle();
            $('li:nth-child(2) > .image').toggle();
        });
        $('#menu > ul:first-child > li:nth-child(3)').hover(function(){
            $('li:nth-child(3) > .image-hover').toggle();
            $('li:nth-child(3) > .image').toggle();
        });
        $('#menu > ul:first-child > li:nth-child(4)').hover(function(){
            $('li:nth-child(4) > .image-hover').toggle();
            $('li:nth-child(4) > .image').toggle();
        });
        $('#menu > ul:first-child > li:nth-child(5)').hover(function(){
            $('li:nth-child(5) > .image-hover').toggle();
            $('li:nth-child(5) > .image').toggle();
        });

现在我想缩短代码,使用"for"循环。这个想法是,我有一个变量I,从1开始,增加1到5。上面的第n个子节点现在不再拥有一个特定的数字,而是保存i。随着i的变化,第n个子节点(i)将拥有i的各自值。

        (function($){
            for (var i = 1; i < 6; i++) {
                $('#menu > ul:first-child > li:nth-child(i)').hover(function(){
                    $('li:nth-child(i) > .image-hover').toggle();
                    $('li:nth-child(i) > .image').toggle();
                });
            };
        })(jQuery);

这个缩短代码不起作用。

有人能帮我一下吗?非常感谢。

如果您想要定位当前悬停元素中的元素,那么您可以在this上下文中使用.find()/.children()(在事件处理程序中,this指的是处理程序所定位的元素——在本例中是li元素),如

//dom ready handler
jQuery(function ($) {
    $('#menu > ul:first-child > li').hover(function () {
        //I think you want to target the child elements of the current li so
        $(this).children('.image-hover').toggle();
        $(this).children('.image').toggle();
    });
});

由于您没有共享目标标记,另一个选择是使用.index()找到当前li的索引,并使用它来定位相同索引中的li,如

//dom ready handler
jQuery(function ($) {
    $('#menu > ul:first-child > li').hover(function () {
        //find the index of the current element
        var i = $(this).index();
        //use i as a variable to find i'th child of li
        $('li:nth-child(' + i + ') > .image-hover').toggle();
        $('li:nth-child(' + i + ') > .image').toggle();
    });
});

这似乎可以完全取代改变css悬停背景样式,而不是使用javascript来切换悬停图像

修改选择器:

$(' #菜单> ul:第一个孩子>李:nth-child ()")
$(" #菜单> ul:第一个孩子>李:nth-child ("我+ +"))

(function($){
            for (var i = 1; i < 6; i++) {
                $('#menu > ul:first-child > li:nth-child('+i+')').hover(function(){
                    $('li:nth-child('+i+') > .image-hover').toggle();
                    $('li:nth-child('+i+') > .image').toggle();
                });
            };
        })(jQuery);

问题是你的代码是把你的i作为i(字母),而不是i作为i(变量),因为你的i在引号中,从i周围删除引号。