js .live的使用
浏览量:863
对于js写入的dom,需要用live去操作.
什么是 .live()
.live方法类似于.bind(),除此之外,它允许你将事件绑定到DOM元素上,可以将事件绑定到DOM中还不存在的元素上,看看下面的例子:
比方说当用户在点击链接时及想提示他们正在离开站点。
1 2 3 4 5 6 | $(document).ready( function()
{$('a').click( function()
{alert("You
are now leaving this site");return true;});}); |
注意,.click()仅仅是个实现更一般.bind()的简单方法,下面和上面的代码相当于上面的实现。
1 2 3 4 5 6 | $(document).ready( function()
{$('a').bind( 'click', function()
{alert("You
are now leaving this site");return true;});}); |
但是现在通过javascript添加一个链接到页面。
1 |
然而当用户点击那个链接是,方法将不会被调用,因为那个链接当你将click事件绑定到页面的所有节点时还并不存在,所以我们就用.live()替换.bind():
1 2 3 4 5 6 | $(document).ready( function()
{$('a').live( 'click', function()
{alert("You
are now leaving this site");return true;});}); |
现在如果你添加一个新的链接到页面上,绑定就也可以运行了。


感谢支持与鼓励~