观察新 DOM 节点的插入并调用它们的方法

发布于 2024-09-07 18:28:16 字数 373 浏览 2 评论 0原文

我正在使用 jQuery 编写一些 javascript,以调用类 datepicker 的所有节点上的方法。

这就是我所拥有的:

$('.datepicker').my_method();

这按预期工作 - 它调用 my_method

但是,我希望能够在使用 datepicker 类插入 DOM 的所有节点上调用 my_method

我想要与 .live 方法类似的功能,而不指定 eventType

我该怎么办?

I'm writing some javascript using jQuery to call a method on all nodes with class datepicker.

Here's what I have:

$('.datepicker').my_method();

This works as expected - it calls my_method.

However, I want to be able to call my_method on all new nodes that are inserted into the DOM with the class datepicker.

I want similar functionality to the .live method, without specifying an eventType.

How do I go about this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反差帅 2024-09-14 18:28:16

这就是 .livequery 插件 的用途

:)或者

$('.datepicker').livequery(function() {
  $(this).my_method();
});

,您可以在加载元素时重新运行插件,例如 $.ajax(),如下所示:

$.ajax({
  //options..
  success: function(data) {
    $("#elementId").html(data);
    $(".datepicker", data).my_method();
  }
});

此方法仅在响应中的 .datepicker 元素上运行,而不是现有的元素......所以它只是运行/做最少的工作。就浪费的观察代码/处理等而言,这是最有效的方法......但它并不总是一个选择。

This is what the .livequery plugin is for :)

You use it like this

$('.datepicker').livequery(function() {
  $(this).my_method();
});

Alternatively, you can re-run your plugin when you're loading elements, say in the case of $.ajax(), like this:

$.ajax({
  //options..
  success: function(data) {
    $("#elementId").html(data);
    $(".datepicker", data).my_method();
  }
});

This method only runs on .datepicker elements in the response, not existing ones...so it's only running/doing the minimal amount of work. This is the most efficient approach in terms of wasted observation code/processing, etc...but it's not always an option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文