当用户完成键入而不是按键盘输入时,jquery-打印用户的输入?

时间:2019-04-21 14:25:41

标签: javascript jquery

我想在用户停止输入时打印其输入。我的html代码是:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="jacoco.css">
  <script src="https://code.jquery.com/jquery-3.4.0.js" integrity="sha256-DYZMCC8HTC+QDr5QNaIcfR7VSPtcISykd+6eSmBW5qo=" crossorigin="anonymous"></script>
  <script src="jacoco.js"></script>

</head>
<body>
  <div class="search">
    <input type="text" id='jacoco' placeholder="Search for a title..">
  </div> 

  <div class="results"></div>

</body>
</html>

我正在尝试执行this帖子中建议的操作,但是它不起作用。我的js代码是:

var typingTimer;                //timer identifier
var doneTypingInterval = 500;  //set wait time until search starts to 5 seconds

//on keyup, start the countdown
$('#jacoco').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#jacoco').val()) {
        alert($("#jacoco").val());
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is finished typing
function doneTyping () {
    alert('$("#jacoco").val();');
}

因此,当我在搜索框中输入内容时,它不会打印我的输入内容。

1 个答案:

答案 0 :(得分:0)

您正在将字符串'$("#jacoco").val();'传递到alert()'应该被删除。并且也使用console.log代替alert()

var typingTimer;                //timer identifier
var doneTypingInterval = 500;  //set wait time until search starts to 5 seconds


//on keyup, start the countdown
$('#jacoco').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#jacoco').val()) {
        //alert($("#jacoco").val());
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is finished typing
function doneTyping () {
   console.log($("#jacoco").val());

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <title>IMDB Search</title>
  <link rel="stylesheet" href="jacoco.css">
  <script src="https://code.jquery.com/jquery-3.4.0.js" integrity="sha256-DYZMCC8HTC+QDr5QNaIcfR7VSPtcISykd+6eSmBW5qo=" crossorigin="anonymous"></script>
  <script src="jacoco.js"></script>

</head>
<body>
  <div class="search">
    <input type="text" id='jacoco' placeholder="Search for a title..">
  </div> 

  <div class="results"></div>

</body>

</html>