[英]How to target an element that is being clicked in a class inside ajax
我想针对某个类中的某些div,我将使用$(this),但这不起作用,因为我从另一个函数调用了该类。
示例代码。
$(document).on('click', '.Player', function(e){
var id = $(this).find('.Song_Id').html();
$.ajax({
type:"POST",
data: {data:id},
complete: function(){
$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png')
},
url:"php/player/get_song.php"
}).done(function(f){
$('#Song_info').html(f)
});
})
从上面开始,以下是我不知道如何暗示的那一行。
$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png'),
它假定目标类是“ .player”,而不是整个类,仅是被单击的元素。
谢谢。
您可以将$(this)
存储在另一个变量中,并在函数中使用此变量。
$(document).on('click', '.Player', function (e) {
var id = $(this).find('.Song_Id').html(),
that = $(this);
$.ajax({
type: "POST",
data: {
data: id
},
complete: function () {
that.attr('src', '../images/appicons/2/16x16/refresh - Red.png')
},
url: "php/player/get_song.php"
}).done(function (f) {
$('#Song_info').html(f)
});
})
执行ajax回调时,默认情况下,回调方法的执行上下文设置为ajax设置对象。
您可以使用$ .ajax()的context选项传递自定义执行上下文
$(document).on('click', '.Player', function (e) {
var id = $(this).find('.Song_Id').html();
$.ajax({
type: "POST",
data: {
data: id
},
//use context to set the execution context of the callback
context: this,
complete: function () {
$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png')
},
url: "php/player/get_song.php"
}).done(function (f) {
$('#Song_info').html(f)
});
})
该对象将成为所有与Ajax相关的回调的上下文。 默认情况下,上下文是一个对象,代表调用中使用的ajax设置($ .ajaxSettings与传递给$ .ajax的设置合并)。 例如,将DOM元素指定为上下文将使该上下文用于请求的完整回调
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.