jQuery - 在load()之后向元素添加功能

Was*_*ace 5 javascript jquery load function append

我有一些代码从另一个文件中加载一些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...
});
Run Code Online (Sandbox Code Playgroud)

我希望它能从上面的url(它们在一个表中)中加载'#editChartForm'表单中找到这些文本框:

<input type="text" name="datefrom" id="datefrom" class="date" /> To: <input type="text" name="dateto" id="dateto" class="date" />
Run Code Online (Sandbox Code Playgroud)

html肯定被加载了.真的很困惑为什么我无法访问load()事件中的任何元素.

我还想在同一个表单上的单击功能应用取消按钮,我发现使其工作的唯一方法是在加载前将其置于"实时"功能中:

$('.cancel').live('click', function() {
  //actions here...
});
Run Code Online (Sandbox Code Playgroud)

有什么想法发生了什么?

Gro*_*ain 7

简单!因为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'));
  });
});
Run Code Online (Sandbox Code Playgroud)