eventListener将添加到父级,但子元素干扰
16lz
2021-01-22
I was trying to create this calculator, and i want that on clicking the whole key/button, the number appears on the screen. However if i click in the h1
region of the key/button, the output is undefined. To understand the problem, try to click the key/button on the white area and then on the blue area. How can i fix that ?
我试图创建这个计算器,我希望在点击整个键/按钮时,数字会出现在屏幕上。但是,如果我单击键/按钮的h1区域,则输出未定义。要了解此问题,请尝试单击白色区域上的键/按钮,然后单击蓝色区域。我该如何解决这个问题?
var evt = document.querySelectorAll(".evt");
var screenText = document.getElementById("screentext");
var show = function(e) {
screenText.innerHTML += e.srcElement.firstChild.innerHTML;
}
for(var i = 0 ; i < 14 ; i++) {
evt[i].addEventListener("click", show);
}
#calcbody {
width: 400px;
height: 500px;
border: 2px solid black;
}
#screen {
width: 90%;
height: 15%;
border: 1px groove black;
margin: 5%;
text-align: right;
}
.flt {
float: left;
width: 20%;
height: 17%;
border: 1px solid black;
box-sizing: border-box;
margin-left: 4%;
margin-bottom: 2%;
position: relative;
}
.flt2 {
float: left;
border: 1px solid black;
box-sizing: border-box;
width: 44%;
height: 17%;
margin-left: 4%;
position: relative;
}
.keys {
text-align: center;
padding-top: 2px;
background-color: skyblue;
}
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="calcbody">
<div id="screen"><h1 id="screentext"></h1></div>
<div id="num1" class="flt evt"><h1 class="keys">1</h1></div>
<div id="num2" class="flt evt"><h1 class="keys">2</h1></div>
<div id="num3" class="flt evt"><h1 class="keys">3</h1></div>
<div id="num4" class="flt evt"><h1 class="keys">4</h1></div>
<div id="num5" class="flt evt"><h1 class="keys">5</h1></div>
<div id="num6" class="flt evt"><h1 class="keys">6</h1></div>
<div id="num7" class="flt evt"><h1 class="keys">7</h1></div>
<div id="num8" class="flt evt"><h1 class="keys">8</h1></div>
<div id="num9" class="flt evt"><h1 class="keys">9</h1></div>
<div id="num0" class="flt evt"><h1 class="keys">0</h1></div>
<div id="plus" class="flt evt"><h1 class="keys">+</h1></div>
<div id="minus" class="flt evt"><h1 class="keys">-</h1></div>
<div id="multiply" class="flt2 evt"><h1 class="keys">*</h1></div>
<div id="divide" class="flt2 evt"><h1 class="keys">/</h1></div>
</div>
</body>
<script src="script.js"></script>
</html>
更多相关文章
- 使用Jquery Ajax更改按钮的颜色(从外部PHP文件接收颜色)
- 带有换行符的文本区域的数据
- 在单选按钮上选中/取消选中,加载/隐藏部分视图
- Ajax的实用技术——用户的注意力从页面的其他区域到转移选择的图
- 彻底解决IE8和IE9下ewebeditor上按钮无效的方法
- 如何在单击按钮时将桌面应用程序导航到系统中设置的默认邮件提供
- 如何在选择单选按钮时显示文本字段
- bootstrap入门【按钮式下拉菜单,输入框组】
- 在AngularJS中轻松控制dom - 单击按钮,然后将焦点设置为输入元素