Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - jQuery - change for only clicked element, not all with the same class

What I would like to do is change an object's attribute, but for only that one. So something like, $('.up img').attr("src","img/up.png") for the one that has been clicked, not all the elements that have .up img.


jQuery:

$('.up img').click( function(){
        var postDataUp = $(this).attr('mod');
        $.post('/votePost.php', {varUp: postDataUp}, function(o){
            console.log(o);
            if(o == 1){
                $('.up img').attr("src","img/up.png");
            }else if(o == 2){
                $('.up img').attr("src","img/up-g.png");
                $('.down img').attr("src","img/dw.png");
            }else if(o == 3){
                $('.up img').attr("src","img/up.png");
            }
        }, 'json');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use $(this) instead to target only the particular element of that class which was clicked on, instead of using the class selector.

$('.up img').click( function(){
        var postDataUp = $(this).attr('mod');
        $.post('/votePost.php', {varUp: postDataUp}, function(o){
            console.log(o);
            if(o == 1){
                $(this).attr("src","img/up.png");
            }else if(o == 2){
                $(this).attr("src","img/up-g.png");
                $('.down img').attr("src","img/dw.png");
            }else if(o == 3){
                $(this).attr("src","img/up.png");
            }
        }, 'json');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...