2012-01-18 45 views
1

我有这样的:的setTimeout使用jQuery功能.live()

function toggle() { 
    $('#clbttn').fadeOut('fast'); 
    $('#msg').fadeOut('fast'); 
    setTimeout(function() { $('#msg').remove(); $('#clbttn').remove(); }, 200); 
} 
$('#clbttn').live('click', toggle()); 

而作为一个结果,我有这样的: 遗漏的类型错误:对象#clbttn有没有方法 '应用'

有谁知道我该做什么?

+0

您传递**返回值**(这是*不*功能)'切换'到'活着'。 – 2012-01-18 16:27:29

回答

4

您应该将toggle()更改为toggle,因为前者是函数调用。

$('#clbttn').live('click', toggle); 
+1

是的,它的工作原理。谢谢!但我仍然有一个问题......为什么它运行好一个月?这真的很奇怪。 – 2012-01-18 16:28:42

0

住的是过时的,jQuery的建议使用on

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.

1

正如杰森说,live已被弃用,并应与on更换。但是,做只是这样做:

$('#clbttn').on('click', toggle); 

不会与动态添加的内容工作,因为它不会建立一个委托的事件处理程序。以上将相当于

$('#clbttn').bind('click', toggle); 

要使用动态添加的内容使用on,你想:

$(document).on('click', '#clbttn', toggle); 

这将告诉jQuery来听冒泡到文档的根的所有点击,并触发当点击来自ID为clbttn的元素时,切换功能。如果你知道该元素将永远只能是,说,id为foo一个div,你可以更有效地写为

$("#foo").on('click', '#clbttn', toggle); 
+0

非常感谢! – 2012-01-20 19:00:57