我正在学习新的jQuery $ .ajax回调语法 问:如果我在$('td.showcities')之外移动req.success。点击功能,那么我应该如何引用$ tr?
// When the user clicks on a state, the list of cities will appear.
$('td.showcities').click(function(){
var $tr = $(this).closest('tr');
var StateID = $tr.data('StateID');
var StateName = $(this).next().text();
var req = $.ajax({
url: 'Remote/City.cfc?queryFormat=column'
,data: {
method:'WhereStateID'
,returnformat:'json'
,StateID:StateID
}
});
req.success(function(result){
$('.highlight').removeClass('highlight');
$('.err').removeClass('err');
if (result.MSG == '') {
$tr.addClass('highlight');
var qryCity = result.qry.DATA; // Normalize
qryCity.RecordCount = result.qry.ROWCOUNT; // Normalize
qryCity.ColumnList = result.qry.COLUMNS; // Normalize
var TableData = '';
for (var i = 0; i < qryCity.RecordCount; i++) {
TableData
+='<tr data-CityID="' + qryCity.CITYID[i] + '">'
+ '<td>' + qryCity.CITYNAME[i] + '</td>'
+ '</tr>';
};
$('#cities tbody').empty().append(TableData);
$('#cities thead th').text(StateName);
} else {
$tr.addClass('err');
$('#msg').text(result.MSG).addClass('err');
};
});
});
答案 0 :(得分:1)
在您可以做的许多不同的事情中,最方便的是将$tr
变量作为context
选项传递给ajax
来电:
var req = $.ajax({
url: 'Remote/City.cfc?queryFormat=column'
,data: {
method:'WhereStateID'
,returnformat:'json'
,StateID:StateID
},
context: $tr
});
在您的成功回调中,$tr
的值将成为this
变量:
req.success(success);
...
function success(result){
$('.highlight').removeClass('highlight');
$('.err').removeClass('err');
if (result.MSG == '') {
this.addClass('highlight'); // <---
...
答案 1 :(得分:1)
您可能会发现this post of mine有用。它解释了jQuery 1.5中AJAX的新deferred/promise API。