我正在尝试学习jquery和twitter bootstrap。我有两种警报:
在页面加载创建的警报上按'x'清除它。按钮加载的那个不会发生同样的情况。我在脚本中遗漏了什么吗?
<div class="container">
<div class="row">
<div class="span12">
<div id="alert-section" class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Page load alert!</h4>
This alert is displayed when page loads.
</div>
<button type="button" id="btn-alert" href="#">Open my alert</button>
<div id="le-alert"></div>
</div>
</div>
</div>
$('#btn-alert').click(function () {
$('#le-alert').addClass('alert in');
$('#le-alert').append('<button type="button" class="close" data-dismiss="alert">×</button><h4>Alert title</h4><p>This alert is dispalyed on button click</p>');
});
$('.close').click(function () {
$(this).parent().removeClass('alert in');
$(this).parent().empty();
});
答案 0 :(得分:4)
您将附加一个类“close”的按钮,但在创建目标按钮之前绑定到该类的所有元素。你需要委派。
$('body').on('click', '.close', function() {
$(this).parent().removeClass('alert in').empty();
});
如果可行,请用较低级别的一致包装替换body
以反转DOM遍历工作。
答案 1 :(得分:3)
当您在按钮中使用'data-dismiss'属性并且第一次关闭按钮时,完整元素将消失,您将不会再次看到该元素,直到您重新加载/刷新页面。因此,如果您希望在没有页面刷新的情况下反复看到警报弹出窗口,请删除data-dismiss属性。
使用jquery的hide()方法关闭警报,而不是从文档对象模型中完全删除它。 有关同样的问题,请参阅此Twitter Bootstrap alert message close and open again。
例如 -
<div class="alert alert-success fade in">
<button type="button" class="close">×</button>
<strong>Sucess!</strong> Values updated!!
关闭按钮的Javascript -
$('.close').click(function () {
$(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3
});
答案 2 :(得分:0)
您要查找的是事件委派,只有当您调用.close
时文档中的$('.close')
div才会绑定点击处理程序。任何创建后的都不会绑定事件处理程序。
$(document).on('click', '.close', function () {
$(this).parent().removeClass('alert in');
$(this).parent().empty();
});
答案 3 :(得分:0)
如果您想在删除提醒消息时获得淡出效果,请尝试以下操作:
<强> HTML 强>
<div class="alert alert-success fade in">
<strong>Well done!</strong> You can remove this important alert message.
<button type="button" class="close">×</button>
</div>
<强> Jquery的强>
$('.alert-success .close').click(function () {
$(this).parent().hide('slow', function(){ $(this).remove(); });
});
答案 4 :(得分:0)
我也遇到了这个问题,只是通过点击事件来攻击关闭按钮的问题是我仍然需要访问标准的bootstrap警报关闭事件。
我的解决方案是写一个small, customisable, jquery plugin注入一个正确形成的Bootstrap 3警报(有或没有关闭按钮,你需要它),最小的麻烦,让你在盒子关闭后轻松重新生成它
有关用法,测试和示例,请参阅https://github.com/davesag/jquery-bs3Alert。