简体   繁体   English

在不使用递归的情况下刷新 javascript 的函数

[英]Refresh javascript's function without using Recursion

I'm trying to create a simple form where i can add more text field after current text field.我正在尝试创建一个简单的表单,我可以在当前文本字段之后添加更多文本字段。

And also i can add more field from the new field that ive added before (im using Recursion for this).而且我还可以从我之前添加的新字段中添加更多字段(为此我使用递归)。

Problems come when i click the add on the first field, it creates more then 1 new fields (this happens because of recursion)当我单击第一个字段上的添加时出现问题,它会创建超过 1 个新字段(这是由于递归而发生的)

how do i refresh javascripts function without calling it again and again?我如何刷新javascripts函数而不一次又一次地调用它?

HTML : HTML :

<div class="line-input">
  <input type='text' class='ipt-txt'>
  <input type='submit' class='btn-smt' value="add new">
</div>

JS : JS:

$(document).ready(function(){
    callFunction();
});

function callFunction(){
    $(".btn-smt").click(function(e){
    $(this).parent(".line-input").clone().insertAfter($(this).parent(".line-input"));
    callFunction();
  });
};

JSFiddle : https://jsfiddle.net/1uofya3k/ JSFiddle: https ://jsfiddle.net/1uofya3k/

Thanks!谢谢!

Use event delegation:使用事件委托:

$(function() {
   $(document).on("click", ".btn-smt", function(e) {
     $(this).parent(".line-input").clone().insertAfter($(this).parent(".line-input"));
   });
});

That sets up an event handler at the document level that responds to clicks on your button class.这会在document级别设置一个事件处理程序,以响应对按钮类的点击。 You only have to add it once, and it'll work for all subsequent elements that are added dynamically.您只需添加一次,它将适用于所有动态添加的后续元素。

(You don't really even have to do it in a "ready" handler; you can set it up before the DOM has been completed.) (您甚至不必在“就绪”处理程序中执行此操作;您可以在 DOM 完成之前进行设置。)

Add true to the clone() function.true添加到clone()函数。 From the jQuery API:来自 jQuery API:

withDataAndEvents (default: false) Type: Boolean A Boolean indicating whether event handlers should be copied along with the elements. withDataAndEvents(默认值:false) 类型:Boolean 一个布尔值,指示是否应与元素一起复制事件处理程序。 As of jQuery 1.4, element data will be copied as well.从 jQuery 1.4 开始,元素数据也将被复制。

https://api.jquery.com/clone/ https://api.jquery.com/clone/

 $(document).ready(function() { callFunction(); }); function callFunction() { $(".btn-smt").click(function(e) { e.stopPropagation(); $(this).parent(".line-input").clone(true).insertAfter($(this).parent(".line-input")); }); };
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="line-input"> <input type='text' class='ipt-txt'> <input type='submit' class='btn-smt' value="add new"> </div>

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

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