How to use delay the execution of a script until something else is done?
I have an ASP .NET page where I use jQuery. I used this function to search an element in the DOM
$(document).ready(function() {
currentID = $('#ctl00_ContentAreaPlaceHolder_hfCurrentID').val();
if (currentID != "") {
window.setTimeout(function() {
$("div[class^='element'][ID='" +currentID + "']").trigger("click");
$(window).scrollTop(500);
}, 6000);
} });
The problem is that when this code is executed al the DOM is not loaded, because I use an ajax call to create the grid that contains the 'element_r1c1' (r means row, and c means column) elements. Thats why I use the window.setTime开发者_开发技巧out to wait until the DOM is loaded, but this only works if the DOM is loaded in less than 6 seconds. So, I need a way to tell this function to execute after the ajax function has ended. For additional info, this code is in the page (.aspx) and the ajax function is in a control (.ascx)
Update:
I have two pages, the BasePage, the GridPage. The control is in the GridPage, and is called by the first page with
$('#tabs').tabs({
select: function(event, ui) {
// default shows All action elements
$.ajax({
url: 'GridPage.aspx?viewingDate=' + $(ui.tab).attr('Date'),
cache: false,
dataType: "html",
success: function(data) {
//debugger;
$('#tabContent').empty().html(data);
}
});
$('#nPaneArea').html('').removeClass().addClass('Pane');
}
});
So you need to execute this script in the success callback of the AJAX script that is loading the grid. As you've tagged this with ASP.NET I guess you are using UpdatePanel to trigger AJAX calls. If this is the case you could use the endRequest event:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
// do the jQuery stuff here
});
Instead of waiting an arbitrary period of time and then executing unconditionally, check to see if you actually got anything with your jQuery selector every couple hundred milliseconds before acting.
function triggerClickOnReady(id) {
return (function() {
var $element = $("#" + id);
if ($element.size() > 0) {
$element.trigger("click");
$(window).scrollTop(500);
} else {
window.setTimeout( triggerClickOnReady(id), 200);
}
});
}
You'll need to return a function so that you can pass in currentId and hold its value with a closure.
Then, in the success
callback in your AJAX request...
success: function(data) {
$('#tabContent').empty().html(data);
triggerClickOnReady(currentId);
}
As I understand, you're trying to execute a function after the DOM loads and you get a reply to an AJAX request.
You can set a flag in each completion handler for these two events, and, in each one, check whether the other flag is set, and, if it is, execute your function.
精彩评论