2012-07-18 2 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-isfully-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가 그다지 변할 필요가 없다는 사실을 지적했다. 초기 선택기를 변경하고 이벤트 이름과 이벤트 맵 다음에 두 번째 인수로'.hover' 선택기를 추가 할 수있다. 핸들러. 그것들은'.on()'을 두번 호출하는 것으로 바꿀 필요가 없다. (이 논평은 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/

관련 문제