简体   繁体   English

jQuery问题:函数在新创建的HTML元素上不起作用

[英]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. 我有两个函数:一个在单击按钮时创建一个新的<textarea> ,另一个函数在单击<textarea> (或模糊,更改等)执行操作。第二个函数根据以下内容选择元素:类名。 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. 似乎第二个功能仅适用于加载页面时存在的那些匹配元素,但不会在任何新创建的<textarea>元素上激活。 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. jQuery将操作分配给使用.test类标记的元素时,您创建的textarea不在周围。 You'll need the live() function to make this work as desired. 您将需要live()函数来按需进行此工作。

$('.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. 现在,任何带有.test标记的元素都将自动在模糊时绑定指定的函数,无论何时创建。

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 . 或者使用jQuery的.delegate()方法将处理程序放置在#add的父#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() . 与使用.live()相比,这是一种更有效的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM