无法使用eventListener更改所需数量元素的css属性,因为元素是由javascript创建的
我试图改变背景颜色的“gridElement”一旦“按钮”被点击 尝试了什么,更改了元素的创建方式,以便在以后包含事件:无法使用eventListener更改所需数量元素的css属性,因为元素是由javascript创建的,javascript,html,css,reference,event-handling,Javascript,Html,Css,Reference,Event Handling,我试图改变背景颜色的“gridElement”一旦“按钮”被点击 尝试了什么,更改了元素的创建方式,以便在以后包含事件: cloneNode()//除非使用eventDelegation,否则无法使用eventListeners,在这种情况下,也没有parentElement来委托事件 jQuery.clone()//事件没有直接绑定到“gridElement”,而是绑定到“button”,因此jQuery.clone()不会深入复制任何关联事件 此外,尝试引用所有GridElement:
- cloneNode()//除非使用eventDelegation,否则无法使用eventListeners,在这种情况下,也没有parentElement来委托事件
- jQuery.clone()//事件没有直接绑定到“gridElement”,而是绑定到“button”,因此jQuery.clone()不会深入复制任何关联事件
- used window.globalVarRef=localVar.//仅引用第一个元素,而不是所有元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
window.allGridElements.style.backgroundColor = 'blue';
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
方法1//appendChild()
const gridContainer=document.getElementById('gridContainer');
函数createPixels(){
设像素=256;
for(k=0;k问题在于changeBkg函数。要选择“gridElement”类的所有元素,您需要使用for循环查找这些元素,然后更改它们的样式。我向grid元素添加了一些基本css,以便我们可以看到颜色的变化。这解决了您的问题吗
.gridElement{
宽度:100px;
高度:100px;
背景:红色;
显示:内联块;
右边距:10px;
}
方法1//appendChild()
const gridContainer=document.getElementById('gridContainer');
函数createPixels(){
设像素=256;
for(设k=0;k