[英]I am unable to understand the execution of following mathematical equation using JavasScript
[英]I am unable to understand the execution of the code
我的代码:
<head>
<!-- All the required scripts and CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.1.14.min.js"></script>
</head>
<body>
<!-- Bootstrap nav-tabs -->
<ul class="nav nav-tabs" id="mainTabs">
<li class="active" ><a href="#home" data-toggle="tab"><span class="glyphicon glyphicon-home"></span> Home</a></li>
<li><a href="#group" data-toggle="tab" >Groups</a></li>
</ul>
<!-- Content of nav-tabs -->
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade active in" id="home">
home
</div>
<div class=" fade tab-pane" id="group" >
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-12">
<h4>Groups</h4>
<button onclick="f5()"> Add Group</button>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap Model -->
<div class="modal fade" id="myModal2">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" >Add New Group</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-md" id="add" >Add</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
function f5() {
$('#myModal2').modal('show');
$('#myModal2').on('click','#add', function (e) {
console.log("new clicked");
$('#myModal2').modal('hide');
});
}
</script>
</body>
现在的问题是:
当我第一次单击ID为“ add”的模型按钮时:
输出:新点击(打印一次)
当我再次单击ID为“ add”的模型按钮时:
现在,输出:单击新(打印两次)
当我再次单击ID为“ add”的模型按钮时:
现在,输出:单击新(打印三遍)
当我再次单击ID为“ add”的模型按钮时:
现在,输出:单击新(打印四次)
为什么会这样? 我已经搜索了堆栈溢出和Google,但是找不到对我有用的东西。 我是Bootstrap的新手,我想要的是每次单击ID为“ add”的按钮时,“ new clicked”都应仅打印一次。
您可能想检查jQuery的.off方法。 似乎您要为同一事物添加多个侦听器,并且您可能想要删除所有侦听器,然后再重新分配以避免同一消息的多个打印。
例如,在您的f5函数中(请从现在开始,为了代码清晰起见,请使用clear函数),您每次执行该元素时都会为其创建一个新的侦听器。 .off()将为您提供帮助,因为在附加新的事件侦听器之前,它将删除以前添加的事件侦听器。
但是,为了以正确的方式执行操作,您应该将事件侦听器的代码附加到一个组中,例如“ addEventListeners()”,然后运行一次该函数。 (如果要在加载页面后向页面添加元素,请使用事件委托)。
function f5() {
$('#myModal2').modal('show');
$('#myModal2').off('click'); // will remove any previous listeners attached with on
$('#myModal2').on('click','#add', function (e) {
console.log("new clicked");
$('#myModal2').modal('hide');
});
}
问候
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.