简体   繁体   English

如何自动map一个function到一个新添加的DOM元素

[英]How to automatically map a function to a newly added DOM element

I'm trying to automate calling a function (initBox) on all elements with class box on the page in vanilla javascript. I have made a functional solution except that it only applies to elements that are on the page when it is loaded.我正在尝试在香草 javascript 页面上的所有带有 class 框的元素上自动调用 function (initBox)。我已经制作了一个功能性解决方案,除了它仅适用于加载时页面上的元素。 If I add an element to the DOM using javascript, the function (initBox) is not called on it.如果我使用 javascript 将元素添加到 DOM,则不会调用 function (initBox)。

Of course I can call the function (initBox) manually after adding the element, but I would like to automate it.当然我可以在添加元素后手动调用 function (initBox),但我想自动化它。

I'm looking for something similar to what jQuery does for events.我正在寻找类似于 jQuery 为事件所做的事情。

For example:例如:

$('table').on('click', 'td', function (event) {
    doSomething();
});

This event is called even if I add the TD element to the table later via javascript.即使我稍后通过 javascript 将 TD 元素添加到表中,也会调用此事件。

Here is my current solution:这是我目前的解决方案:

 function addBox() { var btn = document.getElementsByTagName('button')[0]; var el = document.createElement('div'); el.classList.add('box'); el.innerText = (document.getElementsByTagName('div').length + 1); btn.before(el); } function initBox(el) { el.innerText += ' Initialized'; } document.querySelectorAll('.box').forEach(initBox);
 .box { display: inline-block; border: 1px solid #1f2227; padding: 20px; } button { padding: 20px; }
 <div class="box">1</div> <div class="box">2</div> <button onclick="addBox()">Add box</button>

The OP's problem can be solved just by the usage of a MutationObserver instance where the OP needs the callback from the list off added nodes just to initialize the very nodes which do match the OP's definition of a box . OP 的问题可以通过使用MutationObserver实例来解决,其中 OP 需要从添加的节点列表中进行回调,只是为了初始化与 OP 的box定义相匹配的节点。

 function addBox() { var btn = document.getElementsByTagName('button')[0]; var el = document.createElement('div'); el.classList.add('box'); el.innerText = (document.getElementsByTagName('div').length + 1); btn.before(el); } function initBox(el) { el.innerText += ' Initialized'; } document.querySelectorAll('.box').forEach(initBox); function initializeBoxClassDivOnly(node) { if (node.nodeType === 1 && node.matches('div.box')) { initBox(node); } } function handleNodeInsertion(mutationList/*, observer*/) { for (const mutation of mutationList) { mutation.addedNodes.forEach(initializeBoxClassDivOnly); } }; const observer = new MutationObserver(handleNodeInsertion); observer.observe(document.body, { childList: true, subtree: true });
 .box { display: inline-block; border: 1px solid #1f2227; padding: 20px; } button { padding: 20px; }
 <div class="box">1</div> <div class="box">2</div> <button onclick="addBox()">Add box</button>

Look Into Mutation Observers, they are the new way of observing dom objects, it allows you to run a function when an item is added or removed or modified in a particular DOM element, or if you want you can go old school ( meaning you add event listeners).查看 Mutation Observers,它们是观察 dom 对象的新方法,当在特定 DOM 元素中添加、删除或修改项目时,它允许您运行 function,或者如果您愿意,您可以运行 go 旧学校(意味着您添加事件监听器)。

Mutation Observers ( Recommended Method ) https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver Mutation Observers(推荐方法) https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Old School Evens https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent老派 晚会 https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent

if you want me to write the code, let me know in the comments.如果你想让我写代码,请在评论中告诉我。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM