2013-07-16 59 views
22

首先,问题的小提琴:jsfiddle.net引导酥料饼,。点击里面没有赶上酥料饼的按钮

我使用的是酥料饼,它的内容是HTML,带班“click_me”的按钮。我有jquery听点击“click_me”,它应该会发出警报。但是,它没有。我错过了什么吗?

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

。点击()将仅适用于负载需要使用的)是存在的元素(

$(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答案是大致正确的。这个答案更完整。这个实现更高效。你的脚本不必遍历整个'document'来找到按钮。 –

1

你应该尝试以下操作:

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

当DOM准备好了,你是按钮,这还没有建立,这样一来,每次的酥料饼的上升,你会处理您创建的按钮事件。

0

使用: show.bs.popover - 此事件在调用show实例方法时立即触发。

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