晚上好,
我無法使用單擊事件偵聽器更改 js 創建的 div 的背景顏色。
我已經解決了這些問題,但我對為什么感到困惑,即使我在創建 div 后宣告函式并附加它仍然不會改變顏色。
代碼如下。
<link rel="stylesheet" href="index.css">
<style>
</style>
<script src="script.js" defer > </script>
<body>
<h1> Grid aye? </h1>
<div class="wrapper">
<aside class ="toggleBar"> This is where the switches will go </aside>
<!-- This where the grids are created, using psuedo classes in CSS. -->
<div id="container"></div>
</div>
</body>
</html>
JS
const container = document.getElementById("container");
const gridItem = document.getElementById("grid-item");
// uses a loop to create the required divs
function makeRows(rows, cols) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', cols);
for (c = 0; c < (rows * cols); c ) {
let cell = document.createElement("div");
container.appendChild(cell).className = "grid-item";
};
};
makeRows(16, 16);
function changeGridColor (e) {
e.style.backgroundColor="red";
};
gridItem.addEventListener(`click`,changeGridColor());
誰能指出我哪里出錯了?
我嘗試在附加創建的 div 之前宣告事件偵聽器,但這會在 VSCode 中引發錯誤
uj5u.com熱心網友回復:
const gridItem = document.getElementById("grid-item");
此行將不正確,因為在腳本執行的這一刻,grid-item您的 HTML 中沒有任何元素具有Id 。您需要將此行放在.makeRows(16, 16);
此外,在 中container.appendChild(cell).className = "grid-item";,您添加了一個class,而不是 id。所以const gridItem = document.getElementById("grid-item");不會是正確的,需要是const gridItems = document.querySelectorAll(".grid-item")。
因為這個類有多個 div,你需要回圈它們以附加事件偵聽器。而不是gridItem.addEventListener(click , changeGridColor);,您將需要:
const gridItems = document.querySelectorAll(".grid-item");
for(let gridItem of gridItems) {
gridItem.addEventListener(`click`, changeGridColor);
}
編輯:e.style.backgroundColor = "red";應該是e.target.style.backgroundColor = "red";
uj5u.com熱心網友回復:
另一種解決方案是正確的,那時該元素不存在。但是,如果您添加了更多行,這些新行/網格項將不會附加事件偵聽器。
相反,您可以依靠更通用的事件委托技術來確保所有未來的網格專案都具有事件偵聽器:
// uses a loop to create the required divs
function makeRows(rows, cols) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', cols);
for (c = 0; c < (rows * cols); c ) {
let cell = document.createElement("div");
cell.classes = ['grid-item'];
cell.style.setProperty('height', '24px');
cell.style.setProperty('background-color', 'black');
container.appendChild(cell).className = "grid-item";
};
};
makeRows(16, 16);
function changeGridColor (e) {
e.style.backgroundColor="red";
};
document.addEventListener('click',function(e){
console.log(e.target.classes);
if(e.target && e.target.classes.includes('grid-item')){
changeGridColor(e.target);
}
});
我們添加grid-item該類,然后設定一個單擊事件偵聽器,以便每當單擊網格項類時,顏色都會更改。
這是一個有效的jsfiddle:https ://jsfiddle.net/1e7c2gzu/22/
(另請注意,您最初不會看到您的網格專案,因為它們沒有尺寸,所以我添加了尺寸并將它們設定為黑色,以便您可以看到它們)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470983.html
標籤:javascript html css
上一篇:如何在Firebasev9中洗掉帶有where查詢的檔案?
下一篇:如何將狀態傳播到特定陣列中
