简体   繁体   中英

Call a function when appending an input into DOM using jQuery

I have a page that appends and removes inputs from DOM using jquery. Some of them share a class ("numeric"). Once each input is appended, my code should call.numeric() to every new input with "numeric" class. I defined this block at the beginning of the code,

$('input.numeric')
    .live('load', function() {
        $(this).numeric();
    });

but load seems not to be related to appended nodes after DOM is loaded. Ready event isn't working either.

How could I do that? Thanks mates

Edit: I managed to solve this following @BGerrissen methods in a more general way. I already defined a wrapper for appending (which I called draw), and then each time I append anything, I trigger $(document).trigger('appended') , so it is easy to track anywhere. Then I use

$(document)
     .bind('appended', function() {
        $('input.numeric').numeric();
    });

To do what I need. Cheers

When appending inputs, fire a custom event as well.

var child = $("<input class='numeric' />");
$("#parent").append(child);
child.trigger("appended");

Then you can hook events to it for your purpose:

$('input.numeric')
    .live('appended', function() { // Use .on() method from jQuery 1.7 and up
        $(this).numeric();
    });

NOTE: As of jQuery 1.7, .live() is deprecated. Use.on()

Or use a helper method for firing the event on append.

function appendAndFireAppendEvent( parentExpr , childExpr ){
    var child = $( childExpr );
    $( parentExpr  ).append(child);
    child.trigger("appended");
}

// usage
appendAndFireAppendEvent( "#parentElement" , "<input class='numeric' />" );

NOT ADVISED **

You can also override jQuery's append() method to always fire the "appended" event.

var oldAppend = $.fn.append;
$.fn.append = function( el )
{
   oldAppend.call( this , el ); // DONT convert el to a JQuery object before passing it to oldAppend
   $(el).trigger("appended");
   return $(el); // to allow chaining to work
}

But this will apply to ALL append() calls, wether you want it or not and might possibly break something as I've not investigated stability of this override.

I agree with BGerrissen by using custom events.

Regarding your question: If you're adding more html than just the input you could scan the whole html snippet like below:

var html = '';
html += '<div>';
html += '<input class="numeric" />';
html += '</div>';

var $html_to_add = $(html);

// add html to dom

if ($html_to_add.find('input.numeric').length > 0) {
  // trigger event   
}

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