当您将 href
和 data-dismiss="alert"
标记放入 Bootstrap 警报的链接中时,您不会获得预期的行为。预期的行为是打开链接并关闭警报。我见过它做其中之一,但从未见过两者兼而有之。
<div class="alert alert-danger">
<strong>Oh snap!</strong> Links in Bootstrap alerts are broken:
<a target="_blank" href="http://google.com" class="alert-link" data-dismiss="alert">Go to Google on new tab.</a>
</div>
如何解决这个错误?
这个问题与此非常相似:Following link before closing Bootstrap Alert ,其中针对单个链接的情况给出了非常具体的答案,但这不适用于我的情况。
这是我的警报,希望能够澄清我正在尝试做的事情:
最佳答案
Bootstrap 4 - 多个链接
对于多个链接,您必须以相反的方式解决这个问题。在父级上放置事件监听器并查找子级将不起作用,因为没有关于具体单击了哪个子级的引用传递。
相反,在每个子链接上放置一个事件监听器。然后你就知 Prop 体点击了什么。点击后,就可以触发你的closed.bs.alert
手动在父级上,这很容易从子级中找到。
$('.alert a').on('click', function (e) {
$(e).parent().trigger('closed.bs.alert');
window.open($(e.target).attr('href'));
});
BS4-ML:https://codepen.io/benjaminwfox/pen/vejLzz
Bootstrap 4
您可以通过向每个链接添加事件监听器来将其保留在 Bootstrap 范例中。这本质上与您链接的问题中的答案相同,您只需要根据类选择器而不是特定 ID 应用监听器。这样您就不需要执行任何操作来处理警报的删除。:
$('.alert').on('closed.bs.alert', function (e) {
console.log('Closed, alerted', $(e.target).children('a').attr('href'));
window.open($(e.target).children('a').attr('href'));
})
BS4:https://codepen.io/benjaminwfox/pen/veXOEL
Bootstrap 3
与 4 非常相似,但您必须为 URL 使用自定义标记:
<div class="alert alert-danger">
<strong>Oh snap!</strong> Links in Bootstrap alerts are broken:
<a data-dismiss="alert" data-href="http://www.msn.com" href="#">Go to Google on new tab.</a>
</div>
$('.alert').on('closed.bs.alert', function (e) {
window.open($(e.target).children('a').attr('data-href'));
});
BS3:https://codepen.io/benjaminwfox/pen/bowQQy
非 Bootstrap 选项
如果您想要对整个过程有更多的控制权,可以编写自己的 JavaScript 方法来创建您想要的链接行为。在标记中实现它,如下所示:
<div class="alert alert-danger">
<strong>Oh snap!</strong> Links in Bootstrap alerts are broken:
<a href="#" onclick="jsfunc(this, 'http://google.com')">Go to Google on new tab.</a>
</div>
哪里this
是对 <a>
的引用标签,因此您现在可以对 element
执行任何操作样式,URL 作为 p_url
传递这样您就可以打开链接:
function jsfunc(element, p_url) {
element.parentNode.style.display = 'none';
window.open(p_url);
}
关于javascript - Bootstrap 警报链接,既关闭警报又访问该链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46354814/