![](/img/trans.png)
[英]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.