I have some code which loads some html from another file, which works as it should. But I am struggling to access elements from this newly loaded data.
I have this code:
var widgetSettings = $("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm');
widgetSettings.appendTo(widget.element);
//so far so good...
widget.element.find('.date').each(function(i){
$(this).datetimepicker(); //this doesn't work
console.log('testing... '+$(this).attr('id')); //this doesn't even work...
});
I'd expect it to find these text boxes in the '#editChartForm' form loaded fro开发者_JAVA百科m the above url (they're within a table):
<input type="text" name="datefrom" id="datefrom" class="date" /> To: <input type="text" name="dateto" id="dateto" class="date" />
The html is definitely being loaded. Just really confused as to why I can't access any elements from the load() event.
I also wanted to apply a click function to a cancel button on the same form, and I found the only way to make it work was to put it within a 'live' function before the load:
$('.cancel').live('click', function() {
//actions here...
});
Any ideas what is going on?
Simple! Because the load() method is asynchronous, and your line widget.element.find('.date')
is firing BEFORE there's actually any elements in the DOM that match it! Just use a callback in your load(), like this:
$("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm', function() {
$('div.widgetsettings').find('.date').each(function(i){
$(this).datetimepicker();
console.log('testing... '+$(this).attr('id'));
});
});
$("div").load("url here",function(){
callbacks();
});
function callbacks(){
//put everything that you want to run after the load in here.
//also if the click function is in here it wont need the .live call
}
Edit: Also with the latest version of jQuery you can now use .on instead of .live (its much more efficient) ie.
$(".widgetsettings").on("click",".cancel",function(){
//actions here
});
hope this helps :)
精彩评论