如何在具有相同类 jquery 的特定字段中返回值

How return value in specific field with same class jquery

本文关键字:字段 返回值 jquery 同类      更新时间:2023-09-26

如果您有具有相同类但不同值的字段,我知道有一种方法可以在jquery中使用$(this)发送值,但是在返回函数结果时,我想更新已单击的特定字段?我怎么能做到这一点 $(this) 是更改具有相同类的每个字段。

是在循环中自动生成的,我不想为每个字段使用不同的类。

一定有办法我错过了实现这一目标

这是我的代码。

$(".voteclick").click(function () {
var dynname = $(this).attr('name');
var votevalue = $(this).next().val();
$.ajax({
    url:'http://localhost/wpcomnt/wp-content/themes/smart-mag-child/subrating.php',
    type:"POST",
    data:"dynname=" + dynname + "&" + dynname + "=" + votevalue + "&measure=" + $('#measure').val(),
    dataType:'json',
    success:function (mydata) {
        if(votevalue == 'up') {
            $(this).val('Agree: ' + mydata); // this must not change every .voteclick field it should change only the clicked one ?
        }
        else if(votevalue == 'down') {
            $(this).val('Disagree: ' + mydata); // this must not change every .voteclick field it should change only the clicked one ?
        }
        //$(".voteclick").val('Agree: '+mydata);
    },
    error:function () {
        $(".errormainbtn").slideDown();
    }
 });
});

请阅读此行旁边的评论$(this).val('Disagree: '+mydata);

有很多字段,一旦我单击它,它们就会更改,因为类是相同的,并且自动生成,请告诉我一种方法,我只能更改我单击的字段 类是

 ".votelick"

正如 Wolff 所提到的,您需要在 ajax 调用的选项中设置context:this。默认情况下,在成功函数中,$(this) 引用 jqXHR 对象。如果您的 ajax 调用位于事件处理程序中,并且您设置了 context:this ,则成功函数中的$(this)将改为引用触发处理程序的元素。

这是一个工作示例

$(".voteclick").click(function () {
    var dynname = $(this).attr('name');
    var votevalue ='up';//changed for example
    $.ajax({
        url:'test.php',//changed for example
        type:"POST",
        context:this, //this is the line you need to add
        data:"dynname=" + dynname + "&" + dynname + "=" + votevalue + "&measure=" + $('#measure').val(),
        dataType:'text', //changed from 'json' for my example
        success:function (mydata) {
           if(votevalue == 'up') {
                $(this).val('Agree: ' + mydata); 
            }
            else if(votevalue == 'down') {
                $(this).val('Disagree: ' + mydata); 
            }
        },
        error:function () {
            $(".errormainbtn").slideDown();
        }
     });
});