只是为了简化工作,我在一个简化的示例中解释了我想做的事情。
模态具有“模态”的ID:
var modal = document.getElementById("modal");
var boxes = document.getElementsByClassName("box");
var boxesLength = boxes.length;
单击任何框时,模态都会出现:
for (var i = 0; i < boxesLength; i++) {
boxes[i].onclick = function () {
modal.style.display = "block";
};
}
现在,我希望使用打开的模式中的按钮为单击的框着色。该代码不起作用,但是我最接近的猜测是这样的:
//get the coloring button in the modal which has Id of "green".
var coloring = document.getElementById("green");
coloring.onclick = function () {
boxes[i].style.backgroundColor = "#90EE90";
//closing the modal after clicking which works
modal.style.display = "none";
};
写“ boxes [0]”将为第一个框上色,但这当然不是我想要的。我希望为单击的框上色。
谢谢您的任何投入。美好的一天!
根据要求提供了一些简单的html
//The modal
<div id="modal">
<button id="green">Completed</button>
</div>
//just some boxes
<div class="boxes"></div>
<div class="boxes"></div>
<div class="boxes"></div>
<div class="boxes"></div>
.... 96 more boxes
根据我对问题的理解,您希望背景色显示在单击框上以显示模态。这是我的解决方案。
//to pass it as a global variable between functions
var randomv = {}
var modal = document.getElementById("modal");
var close = document.querySelector('.close')
//get all box
var x = document.getElementById("innerBox").querySelectorAll(".box");
//for each box execute the following
x.forEach(box => {
//on clicking each box, execute a function
box.addEventListener("click", function () {
//this references the parent element which in this case is the box
randomv.parent = this
//display the modal on clicking the box
modal.style.display = "block";
})
});
//hide the modal on clicking the x
close.addEventListener("click", function(){
modal.style.display = "none"
});
function changeColor() {
//first ensure the background color is normal for each box
x.forEach(box => {
box.style.backgroundColor = "white";
});
//reserve the parent element to a variable
var parent_div = randomv.parent
//change the parent's bg color
parent_div.style.backgroundColor = "green";
}
</script>
#modal {
display: none;
}
#innerBox {
width: 100vw;
display: flex;
}
.box{
flex-grow: 1;
}
.close,.box{
cursor: pointer;
}
<div class="container">
<div id="modal">model content
<div class="close"> x </div>
<button onclick="changeColor()">green</button>
</div>
<div id="innerBox">
<div class="box 1">box1</div>
<div class="box 2">box2</div>
<div class="box 3">box3</div>
<div class="box 4">box4</div>
</div>
</div>
我相信您的问题就在这里。您有:for (var i = 0; i < btnsLength; i++) {
,但是应该指的是boxesLength
,所以for (var i = 0; i < boxesLength; i++
。
这将是“事件委托”的理想应用。在此处阅读更多信息:https://javascript.info/event-delegation。
基本上,将单击处理程序放在所有框的父容器上,然后使用target
指向单击的框。这将为您提供1个事件处理程序,而不是100个。
我用“ this”知道了:
for (var i = 0; i < boxesLength; i++) {
boxes[i].onclick = function () {
modal.style.display = "block";
var koko = this;
green.onclick = function () {
koko.style.backgroundColor = "#90EE90";
modal.style.display = "none";
};
};