使用 jquery 的 each() 将点击事件添加到 imgs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8360862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:25:37  来源:igfitidea点击:

using jquery's each() to add click events to imgs

jquery

提问by Infra Stank

I'm using jquery's each() to add click events to a set of imgs , this works fine but i want each img to have a different effect on click it .

我正在使用 jquery 的 each() 将点击事件添加到一组 imgs 中,这很好用,但我希望每个 img 对点击它都有不同的效果。

$('#worksfoot img').each( function() {

    $(this).click( function() {



        $('#entrycontainer').animate({
        marginLeft:  

        },500); })



})

I would like for the first img to set marginLeft as 0 , then increment it 100 for each of the others .

我希望第一个 img 将 marginLeft 设置为 0 ,然后为每个其他 img 增加 100 。

回答by Enrique Moreno Tent

You could try the following solution:

您可以尝试以下解决方案:

$('#worksfoot img').each( function(index) {
    $(this).click( function() {
        $('#entrycontainer').animate({
            marginLeft: 100*index
        },500);
    });
});

回答by prashu132

('#worksfoot img').each( function(index, elem) {
    elem.click( function() {
        $('#entrycontainer').animate({
        marginLeft:  100*index
        },500); })
})

回答by Burning

You shouldn't use multiple id's for different elements. To make it work fine and always try using class instead of id.

您不应该为不同的元素使用多个 id。为了使其正常工作,并始终尝试使用类而不是 id。

回答by f0rza

$('#worksfoot img').each( function(index) {

    $(this).click( function() {

        $('#entrycontainer').animate({
             marginLeft: index * 100 

        },500); })



})