开发者

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

开发者 https://www.devze.com 2023-01-24 09:58 出处:网络
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, ch开发者_C百科an

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, ch开发者_C百科anged, 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().

0

精彩评论

暂无评论...
验证码 换一张
取 消