简体   繁体   中英

Click event listener works just on the second time

This few lines of code suppose to work like a searching algorithm which also suggests keywords. Clicking on a keyword supposed to put the word into the input textbox. The words which can be results are the following: "first", "second".

The problem is that it doesn't work until the second click.

 var database = ["first", "second"]; var founded = true; $( '#list' ).on( 'click', '.list_elem', function() { $("#box").val(this.textContent); $("#list").empty(); }); $("#box").on("change paste keyup", function() { $("#list").empty(); var inputText = $(this).val(); if (inputText.length != 0) { for (var i = 0; i < database.length; i++) { founded = true; for (var j = 0; j < inputText.length; j++) { if(!(database[i][j].toLowerCase() == inputText[j].toLowerCase())) { founded = false; } } if(founded) { $( "#list" ).append('<div class="list_elem">' + database[i] + '</div>'); } } } });
 <input type="text" id="box"> <div id="list"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

This happens when the <input> looses focus and the change event is emitted, your code runs emptying the #list but then immediately after on keyup it repopulates it. You could use theinput event in place of change and keyup to workaround this:

$("#box").on("input paste", function() { ...

 var database = ["first", "second"]; var founded = true; $('#list').on('click', '.list_elem', function() { $("#box").val(this.textContent); $("#list").empty(); }); $("#box").on("input paste", function() { $("#list").empty(); var inputText = $(this).val(); if (inputText.length != 0) { for (var i = 0; i < database.length; i++) { founded = true; for (var j = 0; j < inputText.length; j++) { if (!(database[i][j].toLowerCase() == inputText[j].toLowerCase())) { founded = false; } } if (founded) { $("#list").append('<div class="list_elem">' + database[i] + '</div>'); } } } });
 <input type="text" id="box"> <div id="list"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

This is because the input has focus when typing, the first click makes the input lose focus. The second click actually fires the onClick(); The easiest solution I can think of is removing focus when the mouse enters the list. Here is a link to jQuery's mouseenter() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM