简体   繁体   中英

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)

how do i refresh javascripts function without calling it again and again?

HTML :

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

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/

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. 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.)

Add true to the clone() function. From the jQuery API:

withDataAndEvents (default: false) Type: Boolean A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.

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>

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