[英]click 1 times but alert multiple times in jquery
i run code below , click open 5 times and click close 4 times then click alert .我运行下面的代码,单击打开5 次,然后单击关闭4 次,然后单击警报。 i expected that alert function run 1 times but it run 5 times why?
我原以为警报功能会运行 1 次,但为什么会运行 5 次? , how to prevent this problem?
,如何预防这个问题?
code contains 3 buttons that by click open ,shows two buttons including close and alert button and by click close hides alert and close button and by click alert ,alerts 1.代码包含 3 个按钮,单击打开,显示两个按钮,包括关闭和警报按钮,单击关闭隐藏警报和关闭按钮,单击警报,警报 1。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".close-but").css("display","none");
$(".alert").css("display","none");
$(".open-but").click(function(){
$(".alert").click(function(){
alert("1");
});
$(".open-but").css("display","none");
$(".close-but").css("display","flex");
$(".alert").css("display","flex");
});
$(".close-but").click(function(){
$(".close-but").css("display","none");
$(".alert").css("display","none");
$(".open-but").css("display","flex");
});
});
</script>
</head>
<body>
<button class="open-but">open</button>
<button class="close-but">close</button>
<br/>
<button class="alert">alert</button>
</body>
</html>
You have misplaced $(".alert").click()
你放错了
$(".alert").click()
Every time you hit .open-but
it assigns an event handler for alert
button.每次您点击
.open-but
它都会为alert
按钮分配一个事件处理程序。 You should assign $(".alert").click()
once only.您应该只分配
$(".alert").click()
一次。 So place this outside of $(".open-but").click()
as below:所以把它放在
$(".open-but").click()
,如下所示:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".close-but").css("display", "none"); $(".alert").css("display", "none"); $(".open-but").click(function() { $(".open-but").css("display", "none"); $(".close-but").css("display", "flex"); $(".alert").css("display", "flex"); }); $(".close-but").click(function() { $(".close-but").css("display", "none"); $(".alert").css("display", "none"); $(".open-but").css("display", "flex"); }); $(".alert").click(function() { alert("1"); }); }); </script> </head> <body> <button class="open-but">open</button> <button class="close-but">close</button> <br /> <button class="alert">alert</button> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.