Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

javascript - Stop jquery function from .bind and .MouseUp

Have a jquery where "displayInput" display some hidden input controls, and by clicking outside or pressing enter or escape, back to it hidden state..

.bind and .mouseup only work as soon I run displayInputs, that's ok.. the problem is both still fire to the console.log and I cant find a way to stop them.

function displayInputs(ID){
     //Show Inputs

     $(document).bind('keypress', function(e){
          if (e.which == 13 || e.keyCode == 27){ // escape or enter key
               //Hide Inputs
               console.log('still alive');
               return false;
          }
     });

     // Outside click action
     $(document).mouseup(function(e){
          //Hide Inputs
          console.log('still alive');
          return false;
     }
}

Working JSFiddle

$(document).off(); seems it works but kill other scripts..

question from:https://stackoverflow.com/questions/65939113/stop-jquery-function-from-bind-and-mouseup

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Problem is, that you are assigning the keypress and mouseup to the document. In the functions you should check which was clicked. Check out this (escape not working here...):

 $(document).ready(function() {
        //Show Inputs
        $(document).bind('keypress', function(e) {
            if (e.which == 13 || e.keyCode == 27) { // escape or enter key
                //Hide Inputs
                console.log('keypress');

            }
        });

        // Outside click action
        $(document).click(function(e) {
            //Hide Inputs
            if (e.target.id === "input") {
                console.log("click on input");
            } else {
            console.log('clicked outside');
            }
        });
    })
        body {
            height: 100%;
            font-family: sans-serif;
        }
        
        #input {
            background-color: #cecece;
            padding: 15px;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
    <div id="input">Click Here fires DisplayInput</div>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...