2012-07-18 3 views
8

ホバー状態で動的に作成された要素に問題があります。新しく作成されたhtml要素にカーソルを置くと、機能しません。まだここhttp://api.jquery.com/on/示すようjQuery 1.7 .on()ホバーを作成するには?

$('.hover').on({ 
    mouseenter : function() { 
     alert('you hovered the button!'); 
    }, 
    mouseleave : function() { 
     alert('you removed the hover from button!'); 
    } 

}); 

、ない運:私もこのコードを試してみました

var createBtn = $("#create"); 

createBtn.click(function() { 
    $('div').append('<button class="hover">new hover button</button'); 
    return false;   
}); 


$('.hover').hover(function() { 
    alert('you hovered the button!'); 
}, function() { 
    alert('you removed the hover from button!'); 
}); 

<button id="create">create new button</button> 
<button class="hover">hover me</button> 
<div></div> 

のjQuery:

は、ここに私のHTMLコードです。 デモ:http://jsfiddle.net/BQ2FA/

+0

多分これはオン/オフについて助けになるでしょう:http://stackoverflow.com/questions/11283341/jquery-disable-click-until-animation-is-fully-complete –

答えて

18

これは正しい構文ではありません。

要素の.hover "動的に作成するためにあなたのイベントをリッスンするには使用この:あなたが直接結合のための.onを使用している

$(document).on('mouseenter', '.hover', function(){ 
     alert('you hovered the button!'); 
}).on('mouseleave', '.hover', function() { 
     alert('you removed the hover from button!'); 
}); 
+2

明示的に複数回呼び出す必要がないようにするには、 '.on()'の最初の引数は(OPが現在行っている)オブジェクトであることができます。 (ダウンナイトは私のものではない - この答えはまだ正しい)。 –

+0

@JamesAllardice多くの可能な解決策がありますが、それを短くすることは可能ですが、OPの呼び出しを動的に作成された '.hover'要素に適用することはできません。 –

+1

私は、OPがそれほど変更する必要がないという事実を指摘していました。最初のセレクタを変更し、イベント名とイベントのマップの後に2番目の引数として '.hover'セレクタを追加するだけですハンドラー。彼らはそれを '.on()'への2回の別々の呼び出しに変更する必要はありません。 (コメントはあなたの答えの批判ではなく、OPの利益のためであった)。 –

3

、あなたが委任のためにそれを使用する必要があります。

$('div').on({ 
    mouseenter: function() { 
     alert('you hovered the button!'); 
    }, 
    mouseleave: function() { 
     alert('you removed the hover from button!'); 
    } 
}, ".hover"); 

http://jsfiddle.net/BQ2FA/2/

関連する問題