8

ホバー状態で動的に作成された要素に問題があります。新しく作成したhtml要素にカーソルを合わせると、機能しません。

これが私のHTMLコードです:

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

jQuery:

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!');
});

私もこのコードを試しました:

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

});

ここに示されているようにhttp://api.jquery.com/on/ですが、それでも運がありません。デモもあります:http://jsfiddle.net/BQ2FA/

4

2 に答える 2

18

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

これを使用して、動的に作成された '.hover' 要素のイベントをリッスンします。

$(document).on('mouseenter', '.hover',  function(){
         alert('you hovered the button!');
}).on('mouseleave', '.hover', function() {
        alert('you removed the hover from button!');
});
于 2012-07-18T12:49:22.493 に答える
3

直接バインディングに使用.onしています。委任に使用す​​る必要があります。

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

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

于 2012-07-18T12:52:57.810 に答える