我想将我的代码与网页中的 UI 分开,并且我想知道是否有一个我可以使用的事件,它会告诉我是否创建了一个元素,以便我可以在以下位置为其分配一个事件处理程序:它的创建时间。
例如,如果我有两个元素,并且它们每个都有事件处理程序,我如何知道这些元素何时被创建,然后添加它们?
到目前为止,我所做的是将文档的监听器添加到 addElement
事件(如果存在)。我不知道是否存在。如果是,则检查该元素是否与函数字典中任何现有的 id 匹配。所以像这样:
来自单独脚本文件的代码:
<script>
// event handler for BorderContainer1282
function doSomething1() {
}
// event handler for Button925
function doSomething2() {
}
var clickHandlersDictionary = {};
clickHandlersDictionary["BorderContainer1282"] = doSomething1;
clickHandlersDictionary["Button925"] = doSomething2;
function createComplete() {
document.addEventListener("added", addElementEventHandlers);
}
function addElementEventHandlers(event) {
var element = event.currentTarget;
if (clickHandlersDictionary[element.id]!=null) {
element.addEventListener("click", clickHandlersDictionary[element.id]);
}
}
</script>
和 HTML:
<body onReadyState="creationComplete()">
<div id="BorderContainer1282">
<input id="Button925" type="button" value="Button">
</div >
</body>
我认为我可能想做的是依赖注入(inject),但我不确定。我最终可能会尝试支持状态,并且在创建 HTML 元素时需要添加和删除事件监听器。
最佳答案
您可以使用 MutationObserver 。 MutationObservers 允许您检测 DOM 的更改并做出相应的 react 。
以下面为例:
/*****
Setting up some of your code
*****/
function doSomething1() {
console.log('Do something 1');
}
function doSomething2() {
console.log('Do something 2');
}
var dictionary = {
BorderContainer1282: doSomething1,
Button925: doSomething2
};
/*****
Setting up the observer
*****/
// select the target node
var target = document.getElementById('target');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
Object.keys(dictionary).forEach(function(key) {
var query = target.querySelector('#' + key);
if (query) {
query.addEventListener('click', dictionary[key]);
}
});
});
});
// pass in the target node, as well as the observer options
observer.observe(target, {
childList: true
});
/*****
Just adds to the DOM when you click on the button
*****/
function addToDom(button) {
button.parentNode.removeChild(button);
var parentDiv = document.createElement('div');
parentDiv.textContent = 'Parent';
var childDiv1 = document.createElement('div');
childDiv1.textContent = 'BorderContainer1282 (Click Me)';
childDiv1.id = 'BorderContainer1282';
var childDiv2 = document.createElement('div');
childDiv2.textContent = 'Button925 (Click Me)';
childDiv2.id = 'Button925';
parentDiv.appendChild(childDiv1);
parentDiv.appendChild(childDiv2);
target.appendChild(parentDiv);
}
<button onclick="addToDom(this)">Add to DOM</button>
<div id="target"></div>
MutationObserver 获取目标元素的更改(可以是任何元素,包括 body
)。在这种特殊情况下,它会搜索添加的节点以查找与字典中的元素的任何匹配项。如果找到它们,则会将相应的函数添加到点击监听器中。
关于javascript - 如果我不知道何时创建事件监听器,如何将事件监听器添加到 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38558690/