jQuery 问题:函数无法在新创建的 HTML 元素上运行
我有两个函数:一个函数在单击按钮时创建一个新的
$('#add').click(function() {
$(this).before("<textarea class='test'></textarea>")
})
$('.test').blur(function () {
alert('just a test')
})
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')
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 jQuery 将操作分配给用 .test 类标记的元素时,您创建的文本区域并不存在。您将需要 live() 函数来使其按预期工作。
现在,任何标记为 .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.
Now any element tagged with .test will automatically bind the specified function on blur no matter when it's created.
您可以直接绑定它:
或者使用 jQuery 的
.delegate()
方法将处理程序放置在#add
的父级上。这是比使用
.live()
更有效的方法。You can bind it directly:
Or place use jQuery's
.delegate()
method to place a handler on the parent of#add
.This is a more efficient approach than using
.live()
.