Prevent multiple js files due to the introduction of duplicate registration click event

js file front-end code if it is dynamic is introduced or an event registration operation, then repeat the introduction js file or multiple trigger event causes the event registration to register multiple times, resulting in unnecessary trouble, so it is necessary before each registration will cancel the previous event, click below to register the event of the button as an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../css_com/reset.css">
    <style>

    </style>
    <-! Cdn network to provide jquery, download their own good references as ->
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<input type="button" value="按钮1" id="btn">
<input type="button" value="按钮2" id="btn2">

<script>
// In order to prevent multiple registration event, so before each registration requires advance registration before the click event to remove
    $(function(){
        $("#btn").click(function(){
            $("body").off("click","#btn2").on("click","#btn2",function(){
                alert ( "registered successfully");
            });
        });
    });
</script>
</body>
</html>

  

Guess you like

Origin www.cnblogs.com/SpringAndMoon/p/12105824.html