我有一些代码从另一个文件加载一些html,它的工作方式应该是这样的。但是我很难从这个新加载的数据中访问元素。
我有这样的代码:
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...
});
我希望它能在从上面的url加载的'#editChartForm‘表单中找到这些文本框(它们在一个表中):
<input type="text" name="datefrom" id="datefrom" class="date" /> To: <input type="text" name="dateto" id="dateto" class="date" />
html肯定是在加载。我真的不明白为什么我不能从load()事件中访问任何元素。
我还想在同一个表单上的取消按钮上应用一个click函数,我发现唯一能让它工作的方法就是在加载之前把它放在一个'live‘函数中:
$('.cancel').live('click', function() {
//actions here...
});
你知道是怎么回事吗?
发布于 2011-03-10 16:31:18
很简单!因为load()方法是异步的,并且您的行widget.element.find('.date')
在DOM中实际存在匹配它的任何元素之前就被触发了!只需在load()中使用回调,如下所示:
$("<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'));
});
});
发布于 2011-03-10 16:34:16
$("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
}
编辑:在最新版本的jQuery中,你现在可以使用.on而不是.live (效率更高) ie。
$(".widgetsettings").on("click",".cancel",function(){
//actions here
});
希望这能有所帮助:)
https://stackoverflow.com/questions/5262640
复制