2013-07-16 5 views
22

첫째, 문제의 바이올린이 팝 오버 내부 버튼을 잡기하지 .click. "click_me"에 대한 클릭을 듣기 위해 jquery를 가지고 있으며 경고를 던져야합니다. 그러나 그렇지 않습니다. 내가 놓친 게 있니?부트 스트랩 팝 오버는

JS :

jQuery(document).ready(function($) { 

$('.demo_button').click(function() { 
    $(this).popover({ 
       html: true, 
       trigger: 'manual', 
       placement: 'right', 
       content: function() { 
        var $buttons = $('#popover_template').html(); 
        return $buttons; 
       } 
    }).popover('toggle'); 
}); 

$('.click_me').click(function() { 
    alert('it works!'); 
}); 

}); 

HTML :

<button class="btn btn-primary demo_button">Click here</button> 

<div id="popover_template"> 
    <button class="btn click_me">Make Alert</button> 
</div> 

답변

42

.click()는 당신이 사용할 필요가 부하에 존재하는 요소()

$(document).on("click", ".click_me", function() { 
    alert('it works!'); 
}); 
+0

로드시 생성되지 않았다는 사실에 대해서는 생각하지 않았습니다. 고마워, 이건 완벽한 해답이야! –

3

을 위해 작동합니다 문제는 해당 이벤트를 수신 할 준비가되지 않은 요소에 이벤트를 첨부하는 것입니다. 상위 요소에 이벤트를 첨부해야 요소를 필터링 할 수 있습니다. 이렇게하면 클릭 가능한 요소가 나타나면 문제가되지 않습니다.

<div class="container"><br /> 
    <button class="btn btn-primary demo_button">Click here</button> 

    <div id="popover_template"> 
     <button class="btn click_me">Make Alert</button> 
    </div> 
</div> 

$('.container').on("click", ".click_me", function() { 
    alert('it works!'); 
}); 

또한이 작업을 수행 할 때 너무 높은 상위 나무에 부착하지 마십시오. 가장 가까운 가능한 상위 요소에 연결하려고합니다. document과 같은 클릭 이벤트는 필요하지 않습니다. 특정 이벤트가 발생하는 요소를 구체적으로 나타내는 것이 좋습니다. 이것을 document에 붙이면 click_me 클래스의 모든 요소를 ​​클릭 할 수 있고 동일한 코드에 응답 할 수 있습니다. 다른 버튼에서 다른 기능을 사용하려는 경우 document에 첨부 된 동일한 코드에 모두 응답하기 때문에 다른 기능을 사용할 수 없습니다.

여기에 fiddle입니다.

+0

@stefan 대답은 대체로 정확하지만. 이 대답은 더 완전합니다. 이 구현은보다 효율적입니다. 스크립트는 버튼을 찾기 위해 전체'문서 '를 거치지 않아도됩니다. –

1

는 다음을 시도해야 다음 DOM이 준비되면

jQuery(document).ready(function($) { 

    $('.demo_button').click(function() { 
     $(this).popover({ 
       html: true, 
       trigger: 'manual', 
       placement: 'right', 
       content: function() { 
        var $buttons = $('#popover_template').html(); 
        return $buttons; 
       } 
     }).popover('toggle'); 
     $('.click_me').off('click').on('click', function() { 
      alert('it works!'); 
     }); 
    }); 
}); 

, 당신은 매번 팝 오버는 당신이 만든 버튼의 이벤트를 처리 할 상승, 이렇게,이 아직 생성되지 것 버튼이야.

0

사용 : show.bs.popover -이 이벤트는 show instance 메소드가 호출 될 때 즉시 시작됩니다.

$('#myPopover').on('hidden.bs.popover', function() { 
    // bind your button click event here 
}) 
관련 문제