jquery - 在每个元素上运行函数,但单击的元素除外

Mat*_*hew 7 javascript jquery

作为一些示例代码,我可能会有这样的事情:

$('a.parent').click(function(){

        $('a.parent').each(function(){
            $(this).stop(true,false).animate({
                width: '140px'
            },200,function(){
            });
        });

        $(this).animate({
            width: '160px'
        },200,function(){
        });

    });
Run Code Online (Sandbox Code Playgroud)

问题是我不希望被点击的元素动画为140px宽度,然后再回到160px.

有没有办法只在一组中没有点击的元素上运行'each'?或者,还有更好的方法?

hak*_*ina 24

你可以使用:not(this)so change:

 $('a.parent').each(function(){
            $(this).stop(true,false).animate({
                width: '140px'
            },200,function(){
            });
        });
Run Code Online (Sandbox Code Playgroud)

至 :

$('a.parent:not('+this+')').each(function(){
            $(this).stop(true,false).animate({
                width: '140px'
            },200,function(){
            });
        });
Run Code Online (Sandbox Code Playgroud)

或者在$('a.parent')之后使用.not(this),所以:

$('a.parent').not(this).each(function(){
                $(this).stop(true,false).animate({
                    width: '140px'
                },200,function(){
                });
            });
Run Code Online (Sandbox Code Playgroud)