boostrap警报解雇如何工作?

时间:2017-12-30 15:40:07

标签: javascript css twitter-bootstrap-3

Here是关于bootstrap dismiss的示例:

<div class="alert alert-warning alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span></button>
    <strong>Warning!</strong> Better check yourself, you're not looking too good.
</div>

我不明白附加到button的javascript处理程序如何确定要关闭的div元素。如果有多个div元素包含class="alert alert-warning alert-dismissible"role="alert",框架如何检测要隐藏的正确元素会怎样?

P.S。如果移除了role="alert",它会稳定工作吗?

1 个答案:

答案 0 :(得分:2)

按钮位于alert元素内,事件侦听器可以轻松隔离发生事件的元素,并从该元素遍历到其父元素,兄弟元素等

没有框架的简化示例:

$('.alert .myButton').click(function() {
  // "this" is instance of myButton event occured on
  $(this).closest('div.alert').hide()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert">
  Content 1 <button class="myButton">Hide Content 1</button>
</div>

<div class="alert">
  Content 2 <button class="myButton">Hide Content 2</button>
</div>