无法处理来自引导弹出窗口内容的事件

Cannot handle events from the content of a bootstrap popover

本文关键字:窗口 事件 处理      更新时间:2023-09-26

我需要把一些动态内容在一个引导弹出窗口与多个事件处理,但没有一个被触发。例如:

HTML:

<span id="popover" class="btn btn-default">
    Popover
    <div class="content hide">
        <form id="form">
            <input type="text" class="form-control"/> 
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
        <button id="cancel" type="button" class="btn btn-default">Cancel</button>
    </div>    
</span>
Javascript:

$('#popover').popover({
    html: true,
    placement: 'bottom',
    content: function () {
        return $(this).parent().find('.content').html();
    }
});
$('#popover').on('shown.bs.popover', function () {
    $('#form').submit(function (e) { // never called
        e.preventDefault();
        alert('Form submitted');
    });
    $('#cancel').click(function () { //never called
        $('#popover').popover('hide');
        alert('popover closed');
    });
});

JS小提琴:http://jsfiddle.net/yddRB/

尝试委派一个cancel和submit事件,如下所示:

为取消

$(document.body).on('click',"#cancel",function () {
    $('#popover').popover('hide');
    alert('popover closed');
});
为提交

$(document.body).on('submit','#form',function (e) {
     e.preventDefault();
     alert('Form submitted');
});

事件委托允许我们在父元素上附加一个事件监听器,它将为所有匹配选择器的后代触发,无论这些后代现在存在还是将来添加。

更新小提琴