gpt4 book ai didi

javascript - Jquery Element 类不存在,但事件仍然触发

转载 作者:行者123 更新时间:2023-12-03 11:27:36 24 4
gpt4 key购买 nike

我有这段代码。

点击按钮时,红、绿、蓝必须按顺序显示,但点击事件直接传播到蓝色,而不显示绿色。当我使用 e.stopproagation 时,jQuery 事件监听器仍然附加到不存在的元素类。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Basket | Placelyrics</title>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="index.css">
<script src="jquery.js"></script>
<script src="a.js"></script>
<script>
$(document).ready(function(){
$('.div1shown').click(function(event){
$('.red').hide();
$('.green').show();
$(this).removeClass('div1shown').addClass('div2shown');
console.log('a');

});

$('.container').delegate('.div2shown', 'click', function(event) {
$('.green').hide();
$('.blue').show();
$(this).removeClass('div2shown').addClass('div3shown');
console.log('b');
});
});
</script>
<style>
.box{
width:200px;
height:200px;
display: block;
}

.red{
background-color: red;
}

.green{
background-color: green;
display:none;
}

.blue{
background-color: blue;
display:none;
}

</style>
</head>
<body>

<div class="container">
<div class="box red">

</div>

<div class="box green">

</div>

<div class="box blue">

</div>

<button class="div1shown">submit</button>
</div>

</body>
</html>

最佳答案

您还需要对第一个事件处理程序使用事件委托(delegate)

$(document).ready(function() {
$('.container').delegate('.div1shown', 'click', function(event) {
$('.red').hide();
$('.green').show();
$(this).removeClass('div1shown').addClass('div2shown');
console.log('a');

});

$('.container').delegate('.div2shown', 'click', function(event) {
$('.green').hide();
$('.blue').show();
$(this).removeClass('div2shown').addClass('div3shown');
console.log('b');
});
});
.box {
width: 200px;
height: 200px;
display: block;
}
.red {
background-color: red;
}
.green {
background-color: green;
display: none;
}
.blue {
background-color: blue;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="container">
<div class="box red">
</div>

<div class="box green">
</div>

<div class="box blue">
</div>

<button class="div1shown">submit</button>
</div>

当您像第一种情况一样使用正常的事件处理程序注册时,选择器在注册阶段仅被评估一次,之后选择器永远不会被评估,这就是为什么即使在您更改类之后,第一个处理程序也是如此被处决。但是,当您使用委托(delegate)事件处理程序时,目标元素选择器会延迟执行,以便它可以适应稍后阶段元素发生的更改。

关于javascript - Jquery Element 类不存在,但事件仍然触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26856902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com