[英]How to set event to the Selector which is added class with .classList.add
我想在下面得到结果,但不知道如何。
第一个适用于我的代码。 但是第二个不起作用。
有人可以帮我吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
background-color:yellow;
}
.box.red {
background-color: red;
}
</style>
</head>
<body>
<a href="#" class="button">Click</a>
<div class="box">BOX</div>
<script>
document.querySelector('.button').addEventListener('click', () => {
document.querySelector('.box').classList.add('red');
});
document.querySelector('.box.red').addEventListener('click', () => {
window.alert('You clicked Red Box');
});
</script>
</body>
</html>
问题是,当您那时附加第二个侦听器时,不存在class = red
元素。
您应该将onclick
事件更改为第一个事件中的第二个事件,在这种情况下,请勿使用addEventListener。
let btn = document.querySelector('.button'); btn.onclick = function(){ document.querySelector('.box').classList.add('red'); document.querySelector('.red').onclick = function(){ window.alert('You clicked Red Box'); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 100px; height: 100px; background-color:yellow; } .box.red { background-color: red; } </style> </head> <body> <a href="#" class="button">Click</a> <div class="box">BOX</div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.