jquery $(event.target).closest('td') getting 'lost' when calling same function more than once at the same time
I am having a problem with the below code and I am not sure of the cause.
Scenario summary:
Basically I have a page with several input fields for inline editing, whenever each one is filled, on blur or pressing enter, a javascript function is called which does the following:- shows "loading" instead of the input field
- does an AJAX request to a PHP file
- on completion, then replaces the 'loading' with the user's value
Problem:
The above is working perfectly fine if the user edits 1 input field at a time, but when the user edits a 2nd field while the first one is still 'loading', the javascript gets 'lost' and when the 1st AJAX request completes, the "loading" is still always there, but on the 2nd one it is correctly replaced.Below is the javascript code, I believe the JS confusion is related to "nearestTd", it is as if jquery is 'forgetting' the old nearestTd (from the first call), and only 'remembers' the new one...any suggestions please ?
function action_addSystemCountryLanguageField (event) {
value = $(event.target).val();
nearestTd = $(event.target).closest('td');
var loading=nearestTd.html("<div align='center'><img src='images/loading-small.gif' width='15' height='15' /></div>");
$.ajax({
url: 'actions/pause.php',
type: 'POST',
dataType: 'json',
success: function(response, textStatus, XMLHttpR开发者_高级运维equest) {
nearestTd.html("<span class='editSystemCountryLanguage'>ok</span>");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (typeof console != 'undefined')
console.dir(XMLHttpRequest);
return false;
}
});
}
PHP code, just a simple pause function so I can have an AJX delay & test this bug:
<?php
sleep(1.5);
?>
the code on the page & the jquery 'listener':
$(".addSystemCountryLanguage").live('blur', action_addSystemCountryLanguageField);
$(".addSystemCountryLanguage").keypress(function(e) {
if(e.keyCode == 13) {
action_addSystemCountryLanguageField(e);
}
});
HTML:
<input class='addSystemCountryLanguage' style='width:80px; border: 0;' value='' />
You are accidentally using global variables.
function action_addSystemCountryLanguageField (event) {
var value = $(event.target).val();
var nearestTd = $(event.target).closest('td');
var loading=nearestTd.html("<div align='center'><img src='images/loading-small.gif' width='15' height='15' /></div>");
.
.
.
}
http://www.jslint.com/ will sometimes catch problems like this for you as well.
精彩评论