简体   繁体   English

如何将现有函数添加到新的 createElement 元素

[英]How to add an existing function to new createElement elements

I would like to give newButton the colourChange function.我想为newButton colourChange功能。 I think I need to use DOMNodeInserted but I'm not quite sure how.我想我需要使用DOMNodeInserted但我不太确定如何使用。

let button = document.querySelectorAll('button');
const colours = ['red', 'yellow', 'green', 'blue'];
const colourChange = button.forEach(press => {
    press.style.backgroundColor = colours[0];
    press.addEventListener('click', e => {
        e.target.style.backgroundColor = colours[(colours.indexOf(e.target.style.backgroundColor) + 1) % colours.length];
    });
});

const createButton = document.getElementById('new button');
createButton.addEventListener('click', e => {
    console.log('creating')
    const newButton = document.createElement("button");
    newButton.innerHTML = "click";
    newButton.classList.add('button');
    document.body.appendChild(newButton);
})

Edit to the following编辑为以下

colourChange();
function colourChange(){ 
let button = document.querySelectorAll('button');
const colours = ['red', 'yellow', 'green', 'blue'];
button.forEach(press => {
press.style.backgroundColor = colours[0];
press.addEventListener('click', e => {
    e.target.style.backgroundColor = 
colours[(colours.indexOf(e.target.style.backgroundColor) + 1) % colours.length];
});
});
}
const createButton = document.getElementById('new button');
createButton.addEventListener('click', e => {
console.log('creating')
const newButton = document.createElement("button");
newButton.innerHTML = "click";
newButton.classList.add('button');
document.body.appendChild(newButton);
colourChange();
})

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

相关问题 如何通过createElement()在聚合物中添加扩展元素 - How to add extended elements in polymer by createElement() 使用createElement将新段落添加到现有段落并保持相同的CSS - using createElement to add a new paragraph to existing paragraph and keeping same css 在javascript中,如何使用document.createElement()在表中添加新行? - In javascript, how to add new rows in a table using document.createElement()? 如何在不覆盖现有元素的情况下向同一类的元素添加新文本? - How do I add new text to elements of the same class without overwriting my existing elements? 在功能中动态添加新元素 - Dynamically add new elements in function 如何在使用 document.createElement 创建的多个 li 元素后添加相同的图标 - How to add the same icon after multiple li elements that were created with document.createElement 如何创建一个 function 将新元素添加到空数组(JS)? - How to create a function that will add new elements into an empty array(JS)? 如何在React中动态地在一些现有元素之间添加新元素? - How do I add new elements in between some existing ones dynamically in React? 如何使用createElement创建新表? - How to use createElement to create a new table? 用createElement()创建的新元素不接受全局命令 - New elements created with createElement() aren't accepting global commands
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM