low*_*sun 14 jquery twitter-bootstrap-3
Bootstrap模态事件多次触发,或者更确切地说是之前的一次.我将模态事件包装在一个click函数中,该函数现在返回模态id.
如何确保事件始终只触发一次,并且只有当click函数调用它时?
jQuery的
$('.img-modal').on('click', function () {
// returns #modal-Id
var modalIdClicked = $(this).attr('data-target')
console.log ('modal id clicked from .img-modal = '+ modalIdClicked);
console.log ('.img-modal clicked');
$(modalIdClicked).on('show.bs.modal', function(event) {
console.log ( 'show.bs.modal');
});
});
Run Code Online (Sandbox Code Playgroud)
默认Bootstrap 3.3.2模态HTML
<div class="col-md-7">
<img class="img-modal img-responsive cursor-pointer" data-toggle="modal" data-target="#modal-1" src="www" alt="image">
</div>
<!-- Modal -->
<div class="modal fade top-space-0" id="modal-1" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content cursor-pointer" data-toggle="modal" data-target="#modal-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="#modal-1">CLOSE ×</button>
<h1 class="modal-title">Modal Title</h1>
</div>
<div class="modal-body">
<div class="img-center">
<img class="img-modal img-responsive" src="wwww" alt="image">
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-default" data-dismiss="modal">Close</a>
</div>
</div>
</div>
</div>
<!-- Modal end -->
Run Code Online (Sandbox Code Playgroud)
我确实看过多次触发的jQuery点击事件和
Bootstrap 3 - 远程加载模式创建了重复的javascript事件,看起来这可以通过该.off方法实现.
所以$(modalIdClicked).off().on('show.bs.modal', function(event) {在这种情况下使用了诀窍.
有人可以向我解释为什么.off在这种情况下需要这种方法吗?我无法理解点击的传递方式.
每次点击都会再次点击Bootstrap JS吗?为什么没有.off方法会多次触发事件?
谢谢.
(我想从书中学习jQuery,如果任何人在那里真的有一个很好的书,甚至独一无二的书来读这个,那么,请不要拍我一张纸条,有这么多的存在,并且所有要求自然是最好的..谢谢.)
为什么没有
.off方法会多次触发事件?
因为每次.img-modal单击该元素时,都会为该事件附加一个新的事件侦听器show.bs.modal.这就是为什么show.bs.modal每次点击都会再次触发该事件的原因.
有人可以向我解释为什么
.off在这种情况下需要这种方法吗?
该.off()方法简单地删除先前附加的事件.
您不需要使用该.off()方法.
show.bs.modal您不应该为每个click事件附加事件的事件侦听器,而应该只为类的所有元素添加一个事件侦听器.modal:
$('.modal').on('show.bs.modal', function (event) {
console.log(this.id);
});
Run Code Online (Sandbox Code Playgroud)
在show.bs.modal事件监听器内,this绑定到显示的.modal元素; 因此,您可以识别显示哪个模态.在上面的例子中,this.id将是modal-1.
| 归档时间: |
|
| 查看次数: |
9030 次 |
| 最近记录: |