简体   繁体   English

jQuery在最后一个孩子的按键上设置了输入

[英]Jquery apped input on last-child keypress

I am novice to JS and i have to improve my page functionality using Jquery. 我是JS的新手,必须使用Jquery改善页面功能。 My current Html is: 我当前的HTML是:

<div class="input_fields_wrap">                  
    <div><ul class="inputList"></ul></div>
</div>

Goal is to append new input field after last child element every time user press a key in the last input field. 目标是每次用户在最后一个输入字段中按一个键时,在最后一个子元素之后添加新的输入字段。 But that should happen only once, and after that user can countinue typing without appending new inputs. 但这应该只发生一次,并且在此之后,用户可以在不增加新输入的情况下进行打字键入。 And, if user begin typing in that new appended input, another one should be added and so on. 并且,如果用户开始输入该新的附加输入,则应添加另一个输入,依此类推。 I tryed something like this, but that adds field only once. 我尝试了类似的方法,但是只添加了一次字段。

$(".inputList").last().one("keypress",(function () {
  $(wrapper).append('<li><input type="text" name="key" placeholder="Attribute" /><input type="text" name="value" placeholder="Value"/><a href="#" class="remove_field">Remove</a></li>');
}

When i remove one() , append countinues in every keypress. 当我删除one() ,在每个按键中添加数字。 How should i manage this? 我应该如何处理?

Thanks! 谢谢!

You must define event handler after append elements. 您必须在追加元素之后定义事件处理程序。

 var appendInput=function(){ $('<li><input type="text" name="key" placeholder="Attribute" /><input type="text" name="value" ' + 'placeholder="Value"/><a href="#" class="remove_field">Remove</a></li>').one("keypress",appendInput).appendTo(".input_fields_wrap"); } $(".inputList").last().find("input").one("keypress",appendInput); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="input_fields_wrap"> <div> <ul class="inputList"><input type="text"/></ul></div> </div> 

Or you can simply remove that class from clicked input element please find below snippet for more info 或者您也可以从单击的input元素中删除class ,请在下面的代码段中查找更多信息

 $(document).on("keypress",".addanother",function(){ $(".inputList").append('<li><input type="text" name="key" placeholder="Attribute" /><input type="text" name="value" placeholder="Value" class="addanother"/><a href="#" class="remove_field">Remove</a></li>'); $(this).removeClass("addanother"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="input_fields_wrap"> <div> <ul class="inputList"> <li> <input type="text" name="key" placeholder="Attribute" /> <input type="text" name="value" placeholder="Value" class="addanother" /> </ul> </div> </div> 

Additionally for binding event on dynamically created element please find this answer 此外,对于在动态创建的元素上绑定事件,请找到此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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