简体   繁体   中英

jQuery Issue: functions won't work on newly created HTML element

I have two functions: one that creates a new <textarea> when a button is clicked, and a second function that performs an action when the <textarea> is clicked (or blurred, changed, etc.) That second function selects elements based on a class name. It seems that the second function only works on those matching elements that existed when the page was loaded, but it will not activate on any newly created <textarea> elements. Can anyone figure out why and how to fix this? You'll find the code below. Thanks. --Jake

$('#add').click(function() {
    $(this).before("<textarea class='test'></textarea>")
})

$('.test').blur(function () {
    alert('just a test')
})

The textarea you create isn't around at the time jQuery assigns the action to elements tagged with the .test class. You'll need the live() function to make this work as desired.

$('.test').live('blur', function () {
    alert('just a test')
});

Now any element tagged with .test will automatically bind the specified function on blur no matter when it's created.

You can bind it directly:

$('#add').click(function() {
    $(this).before("<textarea class='test'></textarea>").prev().blur(function () {
        alert('just a test');
    });
});

Or place use jQuery's .delegate() method to place a handler on the parent of #add .

$('#add').click(function() {
    $(this).before("<textarea class='test'></textarea>")
}).parent().delegate('.test','blur',function() {
    alert('just a test');
});

This is a more efficient approach than using .live() .

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