我試圖一些時間間隔后改變一個div的內部HTML。 我得到我想要使用Ajax正確的反應。 但無法取代內HTML的后,并用Ajax響應地選擇。 什么是錯我的代碼..
HTML
51 seconds ago
58 seconds ago
.
.
.
.
.
10 minute ago
?查詢
setInterval(function() {
$( ".time" ).each(function( index ) {
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$(this).html(response);
//alert(response);
}
});
});
}, 5000);
Answer 1:
this是在回調的窗口。 使用給予的價值callback每個:
$( ".time" ).each(function(index , elem) {
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$(elem).html(response);
}
});
});
你并不需要定義一個新的變量來保護this在jQuery已經為您完成。
Answer 2:
當您使用的是異步函數的回調, this在你的回調并非來自同一背景。 您需要保存this在回調中使用的變量。
嘗試這樣的:
setInterval(function() {
$( ".time" ).each(function( index ) {
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
var self = this;
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$(self).html(response);
//alert(response);
}
});
});
}, 5000);
Answer 3:
我認為,$(這)是斷章取義。 嘗試:
setInterval(function() {
$( ".time" ).each(function( index ) {
var $this = $(this);
var sendTime= $(this).attr("data-time");
dataString = "sendtime="+sendTime+"&q=convertTime";
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
$this.html(response);
//alert(response);
}
});
});
}, 5000);
Answer 4:
setInterval(function() {
$( ".time" ).each(function( index ) {
var sendTime= $(this).attr("data-time");
var _thisvariable = $(this);
dataString = "sendtime="+sendTime+"&q=convertTime";
$.ajax({
type: "POST",
url: "data_handler.php",
data: dataString,
cache: true,
success: function(response) {
alert(response);
_thisvariable.html(response);
//alert(response);
}
});
});
}, 5000);
文章來源: Replace inner HTML of a div with Ajax response