gpt4 book ai didi

ajax 请求中的 JQuery 未知 "this"

转载 作者:行者123 更新时间:2023-12-01 07:52:28 26 4
gpt4 key购买 nike

发出ajax请求时,我需要更改类属性,但无法在Ajax请求中访问“this”

$('.shopping').click(function(){
//Get id attribute
var id = $(this).attr('id');

//Send id attribute in Ajax request
$.get('processAddToShopping.php?id='+id, function(data){
if(data == "success"){
//Change attribute if success
$(this).attr('class', 'new'); //CAN'T access "this" anymore
}
});
});

最佳答案

设置上下文变量:

$('.shopping').click(function(){
//Get id attribute
var id = $(this).attr('id');
var that = this;

//Send id attribute in Ajax request
$.get('processAddToShopping.php?id='+id, function(data){
if(data == "success"){
//Change attribute if success
$(that).attr('class', 'new');
}
});
});

关于ajax 请求中的 JQuery 未知 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28091424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com