我需要进行Ajax调用,并让响应更新被单击以触发事件的DOM元素的子元素。 HTML示例:
<div class="divClass">
<p class="pClass1">1</p>
<p class="pClass2">Some text.</p>
</div>
<div class="divClass">
<p class="pClass1">2</p>
<p class="pClass2">Some text.</p>
</div>
<div class="divClass">
<p class="pClass1">3</p>
<p class="pClass2">Some text.</p>
</div>
示例JavaScript代码:
$(document).ready(function(){
$(".divClass").each(
function(e) {
$(this).attr('divValue', $('p.pClass1', this).text());
$('p.pClass1', this).text('?');
$(this).click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "ajax.php",
data: "val=" + $(this).attr('divValue'),
success: function(msg) {
myData = JSON.parse(msg);
$('p.pClass1', this).html(myData.results[0]); // problem exists here
}
});
});
}
);
});
在问题行上,“ this”是指Ajax响应对象。我不知道如何保留上面几行的“ this”上下文,因此我可以使用Ajax调用的响应来更新其内容。
最佳答案
封闭!
$(document).ready(function(){
$(".divClass").each(
function(e) {
$(this).attr('divValue', $('p.pClass1', this).text());
$('p.pClass1', this).text('?');
$(this).click(function(e) {
e.preventDefault();
// Store 'this' locally so it can be closed
// by the function scope below
var self = this;
$.ajax({
type: "POST",
url: "ajax.php",
data: "val=" + $(this).attr('divValue'),
success: function(msg) {
myData = JSON.parse(msg);
// Now used your closed variable here
$('p.pClass1', self).html(myData.results[0]); // problem exists here
}
});
});
}
);
});
关于javascript - 如何在Ajax调用中保留上下文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1751147/