简体   繁体   中英

.click event called twice?

I am not sure whats wrong but I am trying this code in chrome or Firefox and I am getting the event to be triggered twice any help? I am geting an empty extra "< li > < /li>"

HTML code

  <div id="nav">
 <ul>
   <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
    <li>Bread</li>
 </ul>

  <!-- Input field -->

  <input type="submit" name="search" value="Add" id="submit" style="float:   right" />
 <div style="overflow: hidden; padding-right: .5em;">
  <input id="box" type="text" name="add" value="" style="width: 100%;" />
  </div>

</div>

Jquery code

<script>


  $('#submit').click(function(e){

      var add = $("#box").val();
         if(add !="")
             $("#nav ul").append("<li>"+add+"<li>");
       e.preventDefault();
       e.stopPropagation();
   });

   $('#box').keypress(function(e){
       var add = $("#box").val();
       if(e.which == 13)//Enter key pressed
       $("#nav ul").append("<li>"+add+"<li>");

    });


 </script> 

The click event is not being triggered twice, the problem is you are doing this

$("#nav ul").append("<li>"+add+"<li>"); 

Which is two open <li> tags. So it gets outputted as <li>entered text</li> and <li></li> . Do this instead:

$("#nav ul").append("<li>"+add+"</li>"); //close the tag

See this fiddle

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