简体   繁体   中英

Click Once For All Elements In Same Class

I am trying to write code that will add another row to a form automatically. It should only do this once for each form input with the class lastName.

The below code works. But it executes more than once. I want the code to only execute once for each form input with the class lastName. I am inexperienced with jquery and javascript, so I am unsure of how to approach this problem.

    function AutoAdd() {
    $('.lastName').focus(function(e){
    $('#add_new',pupils_form).parent().before(pupils_row);

    AutoAdd();
    });
    };
    AutoAdd();

You can use the one method:

Attach a handler to an event for the elements. The handler is executed at most once per element.

$('.lastName').one('click', function(e){
      $('#add_new',pupils_form).parent().before(pupils_row);
});

Also as you are binding a handler for the inputs you can put the handler outside of the function, note that your function calls itself and runs continuously. If you want to execute the handler on page load you can trigger the event:

$('.lastName').focus(function(e){
      $('#add_new',pupils_form).parent().before(pupils_row);
}).focus()

For dynamically generated elements, you should delegate the event, try the following:

$(document).on('focus', '.lastName', function(){
     $('#add_new',pupils_form).parent().before(pupils_row);
})

You can use data-* attributes, try the following:

<input type='text' class='lastName' data-run='go'/>

$(document).on('focus', '.lastName', function(){
     if ( $(this).data('run') == 'go') {
           $('#add_new',pupils_form).parent().before(pupils_row);
           $(this).data('run', 'stop')
     }
})

you are having an infinite call stack here. your AutoAdd will call itself again and again and ...

To avoid having to run your AutoAdd function on newly created rows, you can use jQuery's on() -function instead of focus() :

$('#the-form').on('focus', '.lastName', function () {
    $('#add_new',pupils_form).parent().before(pupils_row);
});

on() actually attaches to the form (you'll wanna change the selector #the-form ) and listens to events that bubble up from children of said form.

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