简体   繁体   English

如何在不使用自定义触发器的情况下使用 jQuery 侦听插入到 DOM 中的元素?

[英]How can I listen for an element being inserted into the DOM with jQuery without using custom triggers?

I want to listen for another piece of code that inserts some html into the page.我想听另一段在页面中插入一些 html 的代码。 I don't control that code, so I can't do .trigger('custom_event') and $(document).on('custom_event')我不控制那个代码,所以我不能做.trigger('custom_event')$(document).on('custom_event')

Additionally, the inserted div that I want to listen for is nested inside of the inserted html.此外,我要监听的插入的 div 嵌套在插入的 html 中。

Here's what I have right now:这是我现在拥有的:

$(document).on('DOMNodeInsertedIntoDocument', "#inserted", function () {
    console.log("Inserted into document:", $(this));
});

$(document).ready(function () {
    var new_node = $('<div><div id="inserted">New Div</div></div>');
    $("body").append(new_node);
});

http://jsfiddle.net/AeHxQ/5/ http://jsfiddle.net/AeHxQ/5/

Why doesn't the event get triggered?为什么没有触发事件?

You can use CSS animations with a little JavaScript, to detect when an element has been added to the DOM.您可以使用带有一点 JavaScript 的 CSS 动画来检测元素何时被添加到 DOM。 The technique is explained here: http://davidwalsh.name/detect-node-insertion该技术在这里解释:http: //davidwalsh.name/detect-node-insertion

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用 jQuery 在 DOM 中创建一个没有它的 DOM 元素吗? - Can I create a DOM element without it being in the DOM using jQuery? 我如何知道当前使用jQuery的DOM元素是否在屏幕上 - How can I know if an DOM element is currently on screen using jQuery 如何使用jQuery删除不在DOM上的元素? - How can I remove an element that is NOT on the DOM using jQuery? 如何将事件侦听器附加到本身已使用Javascript插入的元素上? (没有jQuery) - How can I attach an event listener to an element that has itself been inserted with Javascript? (without jQuery) 在 HTMX 中使用多个自定义事件作为触发器,我可以识别正在使用的触发器吗? - Using multiple custom event as triggers in HTMX, can I identify which of the triggers is being used? 渲染为jQuery插入DOM的元素 - Render to element inserted to DOM by jQuery 如何判断是否使用jQuery拖动了元素? - How can I tell if an element is being dragged using jQuery? 使用jQuery获取通过DOM操作插入的表单元素的值 - Get value of form element inserted with DOM manipulation, using jQuery 将元素插入DOM后,如何对元素执行jQuery函数? - How do I perform a jQuery function on an element after it has been inserted into the DOM? 在 jQuery 中完成 ajax 请求后,如何监听 DOM 中的元素? - How to listen to an element in the DOM after its ajax request completes in jQuery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM