jQuery - 仅针对单击元素进行更改,而不是所有具有相同类的更改 [英] jQuery - change for only clicked element, not all with the same class

查看:109
本文介绍了jQuery - 仅针对单击元素进行更改,而不是所有具有相同类的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是更改对象的属性,但仅限于那个。类似于 $('。up img')。attr(src,img / up.png)对于已被点击的那个,不是全部具有 .up img 的元素。

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');
});


推荐答案

使用 $(this) 而是仅定位被点击的该类的特定元素,而不是使用类选择器。

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');
});

这篇关于jQuery - 仅针对单击元素进行更改,而不是所有具有相同类的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆