在动态创建的元素上自动调用 jQuery 插件

发布于 2024-12-27 06:21:20 字数 841 浏览 4 评论 0原文

我需要将 jQuery 插件应用到将根据用户输入创建的 HTML 元素。例如:

<!-- Upon click, this link creates a new div with an id of 'target'. -->
<a id="trigger-a" href="javascript:void(0);">Create a new div</a>

/* This will not work because div#target isn't available yet upon page load. */
$(function() {
  $("div#target").aJQueryPlugin( ... );
});

在最简单的形式中,我可以在创建 div 之后在 的点击处理程序中调用插件。

$(function() {
  $("#trigger-a").click(function() {
    // Create div#target.

    // I can call the plugin here but is there a different, maybe better, way?
    $("div#target").aJQueryPlugin( ... );
  });
});

然而,如果可能的话,我正在寻找更“自动”的东西;也许使用 .on() 在元素可用后自动调用插件?

解释问题: 在 jQuery 中,有没有一种方法可以“监视”某个元素何时可用(即创建后)?如果有,我会调用插件或其他函数作为回调。

I need to apply a jQuery plugin to an HTML element that will be created upon a user's input. For example:

<!-- Upon click, this link creates a new div with an id of 'target'. -->
<a id="trigger-a" href="javascript:void(0);">Create a new div</a>

/* This will not work because div#target isn't available yet upon page load. */
$(function() {
  $("div#target").aJQueryPlugin( ... );
});

In the simplest form, I can call the plugin inside the <a>'s click handler, after the div is created.

$(function() {
  $("#trigger-a").click(function() {
    // Create div#target.

    // I can call the plugin here but is there a different, maybe better, way?
    $("div#target").aJQueryPlugin( ... );
  });
});

However, if possible, I am looking for something that is more "automatic"; maybe using .on() that automatically invokes the plugin once the element becomes available?

Paraphrasing the question:
In jQuery, is there a way to "monitor" when a certain element becomes available (i.e. after it's being created)? If there is, I'd then call the plugin or other functions as a callback.

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

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

发布评论

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

评论(7

扶醉桌前 2025-01-03 06:21:20

您可以使用“DOMNodeInserted”,它不是 jQuery 事件。

$(document).bind('DOMNodeInserted', function(event) {

//write your stuff here to check if desired element was inserted or not.

    alert('inserted ' + event.target.nodeName + // new node
        ' in ' + event.relatedNode.nodeName); // parent
});

You can use 'DOMNodeInserted' which is not a jQuery event.

$(document).bind('DOMNodeInserted', function(event) {

//write your stuff here to check if desired element was inserted or not.

    alert('inserted ' + event.target.nodeName + // new node
        ' in ' + event.relatedNode.nodeName); // parent
});
不…忘初心 2025-01-03 06:21:20

也许是这样的?

HTML

<a id="trigger-a" href="javascript:void(0);">Create a new div</a>

<div class="cont"></div>

JS

$("#trigger-a").click(function () {
    var $div = $('<div>', {class: 'target', text: 'text'});
    $('.cont').append($div);
    $div.trigger('divCreate');
});

$('.cont').on('divCreate', 'div.target', function () {
    $(this).append('added by event')
});

http://jsfiddle.net/Q2UYC/

触发自定义事件让您稍后绑定事件处理程序。

Maybe something like this?

HTML

<a id="trigger-a" href="javascript:void(0);">Create a new div</a>

<div class="cont"></div>

JS

$("#trigger-a").click(function () {
    var $div = $('<div>', {class: 'target', text: 'text'});
    $('.cont').append($div);
    $div.trigger('divCreate');
});

$('.cont').on('divCreate', 'div.target', function () {
    $(this).append('added by event')
});

http://jsfiddle.net/Q2UYC/

Triggering custom event let you bind event handler later.

摇划花蜜的午后 2025-01-03 06:21:20

如果您必须在调用插件之前检查该元素是否存在,您可能可以尝试这样的操作:

$('#click-here').click(function() {
    $(this).after('<button class="new-button">I am a new button</button>');

    var checkElement = setInterval(function() {
        if ($('.new-button').length) {
            $('.new-button').button({'label': 'I am a new fancy button'});
            clearInterval(checkElement);
        }
    }, 200);
});

您可以看到它正在工作

请注意,.button 函数是 jQuery UI 插件初始化,因此它也应该适用于您需要的插件。您还应该将 setInterval 第二个参数更改为其他值,200 只是为了显示延迟。

If you must check the element is there before calling the plugin, you could probably try something like this:

$('#click-here').click(function() {
    $(this).after('<button class="new-button">I am a new button</button>');

    var checkElement = setInterval(function() {
        if ($('.new-button').length) {
            $('.new-button').button({'label': 'I am a new fancy button'});
            clearInterval(checkElement);
        }
    }, 200);
});

You can see it working here.

Note that the .button function is a jQuery UI plugin initialization, so it should also work for the plugin you need. You should also change the setInterval second argument to something else, 200 is just to show a delay.

不及他 2025-01-03 06:21:20

jQuery 的 delegateon 对此都很有用。请注意,如果您使用旧版本的 jQuery,则可以使用 delegate,但如果您使用最新版本 (1.7+),则需要使用 on

对于这些,您必须使用已加载的元素调用方法,并使用参数指定触发事件的元素。为了使其尽可能高效,该元素应该是最接近动态创建的元素的父元素。

例如,如果单击锚标记,您将 id 为“target”的 div 放入在调用 on 之前已加载的容器中,ID 为“container”,您的 < code>on 调用应该是。

$('#container').on('click', '#target', function(){ $(this).pluginCall(); });

您不能简单地调用 #target div 上的 on ,因为该元素尚未加载。

另一个解决方案是将 $(document).ready() 函数内联到调用插件的动态创建的内容中。在这种情况下,您不需要 ondelegate ,但这仅适用于当前加载的元素。在第一个示例中,从任何 ajax 调用创建的 #target 的任何实例都将是 click 处理程序。

jQuery's delegate and on are both good for this. Note that if you use older versions of jQuery you can use delegate but if you use the latest version (1.7+) you need to use on.

With these you must call the method using an element that is already loaded and use a parameter to specify to element that fires the event. To make this as efficient as possible this element should be the closest parent to the dynamically created element.

For instance if on click of the anchor tag, you place a div with id of 'target' into a container that was already loaded before the call to on, with an id of 'container', your on call should be.

$('#container').on('click', '#target', function(){ $(this).pluginCall(); });

You cant simply just call on onto the #target div because that element has not been loaded yet.

The other solution is to place a $(document).ready() function inline into your dynamically created content that calls your plugin. You wont need on or delegate in this instance but this will only work for the currently loaded elements. In the first example, any instance of #target that gets created from any ajax call will be the click handler.

誰認得朕 2025-01-03 06:21:20

我也有兴趣查看插入新 DOM 对象的代码。让我们假设它是这样的:(你真的不应该使用 onclick 处理程序)

$("#trigger-a").click(function() {
    $(this).after('<div id="someDiv"></div>');

    $that = $("#someDiv");

    $that.ajQueryPlugin(...);
});

在没有看到更多信息的情况下我能做的最好的事情就是...

单击触发器,插入新的 div,抓取该对象并在其上运行插件。基本上,您在创建时对 div 进行操作,无需“监视”。

I would also be interested to see the code that inserts the new DOM object. Let's assume it's something like this: (you really shouldn't be using onclick handlers)

$("#trigger-a").click(function() {
    $(this).after('<div id="someDiv"></div>');

    $that = $("#someDiv");

    $that.ajQueryPlugin(...);
});

Is the best I can do without seeing more information...

Click the trigger, insert the new div, grab that object and run the plugin on it. Basically you're operating on the div at the time of creation, no need to 'monitor'.

何以心动 2025-01-03 06:21:20

如果您无法在创建元素的同时引入插件(如评论中建议的 andbeyond),无论出于何种原因,我的建议是使用 Brandon Aaron 的 LiveQuery 插件:

http://brandonaaron.net/code/livequery/docs

...Live Query 还能够在匹配新元素时触发一个函数(回调),并在元素不再匹配时触发另一个函数(回调)。这提供了终极的灵活性和无数的用例。

希望这有帮助:)

If you can't bring the plugin in at the same time as the element creation (like andbeyond suggested in their comment), for whatever reason, my advice would be to use Brandon Aaron's LiveQuery plugin:

http://brandonaaron.net/code/livequery/docs

...Live Query also has the ability to fire a function (callback) when it matches a new element and another function (callback) for when an element is no longer matched. This provides ultimate flexibility and untold use-cases.

Hope that's helpful :)

旧梦荧光笔 2025-01-03 06:21:20

您可以使用 live()on() 来实现此目的

$(document).ready(function(){
    $('div#target').on('click',function(){});
});

You can use live() or on() for this

$(document).ready(function(){
    $('div#target').on('click',function(){});
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文