2012-01-18 7 views
1

私はこれがあります。のsetTimeout()

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

を、結果として、私はこの持っている: キャッチされない例外TypeErrorを:オブジェクト#clbttnは、方法はありませんが、誰もが

を知っています '適用します'私は何をすべきか?

+0

としてこれを書くことができます)の 'toggle'を' 'live''にします。 –

答えて

4

toggle()toggleに変更する必要があります。前者は関数呼び出しであるためです。ライブ

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

うん、それは動作します。ありがとうございました!しかし、私はまだ質問があります...なぜそれは1ヶ月間うまくいきましたか?それは本当に奇妙です。 –

0

廃止され、jqueryのは、ジェイソンがliveは廃止され、そしてonに置き換える必要があり、言ったように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

を使用することをお勧めします。しかし、ないを行うだけでこれを行う:それは委任イベントハンドラを設定しないので、動的に追加されたコンテンツでは動作しません

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

。上記動的に追加されたコンテンツとonを使用するには

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

に相当します、あなたがしたい:

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

は、このドキュメントのルートまで泡立てるすべてのクリックに耳を傾けるのjQueryを伝え、そして起動しますidがclbttnの要素からのクリックが発生した場合は、関数を切り替えます。あなたはこの要素は唯一、これまでになります知っている場合は、たとえば、ID fooとのdiv、あなたはより効率的にあなたが機能* *されていない(**戻り値を渡している

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

ありがとうございます! –