【问题标题】:jQuery - add functionality to element after load()jQuery - 在 load() 之后向元素添加功能
【发布时间】:2011-03-10 16:25:32
【问题描述】:

我有一些代码可以从另一个文件加载一些 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() 事件中访问任何元素。

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

$('.cancel').live('click', function() {
  //actions here...
});

有什么想法吗?

【问题讨论】:

标签: javascript jquery function append load


【解决方案1】:

简单!因为 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'));
  });
});

【讨论】:

  • +1 表示漂亮的代码 sn-p。我有一个类似的问题,但响应缺乏这种清晰度和描述。我敢肯定,这座小山对我的情况以及遇到这种情况的许多其他人都有帮助。
  • 完美!这也解决了我的问题。我需要获取我使用 .load 加载的元素的宽度 - 将它放在回调中修复它!谢谢!
【解决方案2】:
$("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(效率更高),即。

$(".widgetsettings").on("click",".cancel",function(){
    //actions here
});

希望这会有所帮助:)

【讨论】:

  • 是的,感谢您的回复。不幸的是,'Groovetrain' 打败了你 :)
猜你喜欢
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 2018-11-18
  • 2013-05-15
  • 2011-08-10
  • 2011-10-22
相关资源
最近更新 更多