jQuery绑定事件根本不起作用 [英] jQuery bind event does not work at all
本文介绍了jQuery绑定事件根本不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我竭尽所能使它实现,但是没有成功.
I did everything I could to make it happen, but without success.
问题是我在运行时创建一个元素,然后将函数绑定到该元素,如以下代码所示:
The problem is that I create an element on runtime then bind a function to the element like the following code:
$(document).ready(function() {
$('.rem').click(function() {
$("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
});
$('#runtime').bind('click', func_name());
});
//End of doc
function func_name() {
alert('I got it!');
}
在HTML代码中,我有一个如下标签:
In the HTML code I have a label like below:
<div id="body">
<label class="rem">click me</label>
</div>
我的第二次尝试
$(document).ready(function() {
$('.rem').click(function() {
$("body").append('<a id="runtime" href="javascript:void(0);">runtime</a>');
});
$('#runtime').bind('click',function() {
alert($(this).text());
});
});
//End of doc
HTML代码:
<div id="body">
<label class="rem">click me</label>
</div>
推荐答案
更改
$('#runtime').bind('click',func_name());
到
$('#runtime').live('click',func_name);
或(从jQuery 1.7开始):
or (as of jQuery 1.7):
$('#runtime').on('click',func_name);
需要注意的两件事:
- 我将
func_name()
更改为func_name
.绑定处理程序时,您不想调用该函数,而只想引用它. - 呼叫
bind
不会带来任何好处,因为#runtime
直到您单击.rem
之后才存在.这就是为什么您需要live
或on
(取决于jQuery版本)的原因.
- I changed
func_name()
tofunc_name
. You don't want to call the function when you bind the handler - you just want to reference it. - Calling
bind
won't do you any good, because#runtime
doesn't exist until after you've clicked.rem
. That's why you need eitherlive
oron
(depending upon your jQuery version).
出于良好的考虑:此处是您为何仍应使用jQuery.on
的良好参考.
And just for good measure: here's a good reference on why you should be using jQuery.on
anyway.
这篇关于jQuery绑定事件根本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文