获取触发bootstrap模态隐藏的元素的id

时间:2015-04-04 05:51:52

标签: jquery twitter-bootstrap-3

我有一个bootstrap模式,它有几个元素可以在点击时触发hide事件。我希望获得触发事件的元素的id。

我尝试使用event.target以及event.relatedTarget,但两者都无效。

模态的

代码是

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <ul class="nav nav-pills nav-stacked" style="max-width: 300px;">
    <li class="active"><a href="javascript:void(0)" data-dismiss="modal" id='link1'>Link 1</a></li>
    <li><a href="javascript:void(0)" data-dismiss="modal" id='link2'>Link 2</a></li>
    <li><a href="javascript:void(0)" data-dismiss="modal" id='link3'>Link 3</a></li>
</ul>
      </div>
      <div class="modal-footer">
        <button id='btn1' type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

而js代码是

$(document).on('hidden.bs.modal', '#GSCCModal', function (event) {
  var target = $(event.relatedTarget);
  console.log(target.id);
});

2 个答案:

答案 0 :(得分:0)

请尝试以下脚本

$(document).on('hidden.bs.modal', '#GSCCModal', function (event) {
  var id = $(this).attr("id") == undefined ? "NO-ID" : $(this).attr("id") ;
  console.log(id);
});

答案 1 :(得分:0)

我通过给所有触发模态隐藏和使用他们的点击事件的元素提供公共类来解决这个问题。

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <ul class="nav nav-pills nav-stacked" style="max-width: 300px;">
    <li class="active"><a href="javascript:void(0)" data-dismiss="modal" id='link1' class="close">Link 1</a></li>
    <li><a href="javascript:void(0)" data-dismiss="modal" id='link2' class="close">Link 2</a></li>
    <li"><a href="javascript:void(0)" data-dismiss="modal" id='link3' class="close">Link 3</a></li>
</ul>
      </div>
      <div class="modal-footer">
        <button id='btn1' type="button" class="btn btn-default close" data-dismiss="modal">Close</button>
        </div>
    </div>
  </div>
</div>

和js是

$( document ).ready(function() {
  $('.close').on('click', function(event) {
  console.log($(this).attr('id'));
});
});