我正在使用“材质对话框”来确认表中的“删除行”。 第一次从对话框中删除可以删除一行。但是在dialog.close();之后当我第二次调用时,一次单击就执行两次。然后第三次调用对话框并单击“删除”,它将执行3次,包括最近的执行。
dialog.querySelector('.count').addEventListener('click', function() {
请帮助执行此对话框click事件上的仅一个函数调用。谢谢。
var count = 0;
var dialog = document.getElementById('dialog1');
function showdialog() {
dialog.showModal();
dialog.querySelector('.close').addEventListener('click', function() {
dialog.close();
});
dialog.querySelector('.count').addEventListener('click', function() {
count += 1;
dialog.close();
document.getElementById('result').innerHTML = "Result Clicked on Count+1 = " + count;
});
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<body>
<div id='result'>Result = 0</div>
<button id="show-dialog" type="button" class="mdl-button" onclick='showdialog()'>Show Dialog</button>
<dialog class="mdl-dialog" id='dialog1'>
<h4 class="mdl-dialog__title">Allow data collection?</h4>
<div class="mdl-dialog__content">
<p>
Allowing us to collect data will let us get you the information you want faster.
</p>
</div>
<div class="mdl-dialog__actions">
<button type="button" class="mdl-button count">Count +1</button>
<button type="button" class="mdl-button close">Close</button>
</div>
</dialog>
</body>
答案 0 :(得分:0)
因为每次调用showDialog(单击显示对话框按钮)时,每次都添加新的click事件侦听器,并且每个事件侦听器增加计数值,都会导致这种增加(1、3、6、10、15-实际的增量会向您显示.count
有多少事件监听器。)
在showDialog中将.count元素移出addEventListener
将解决此问题,请参见下面的代码:
var count = 0;
var dialog = document.getElementById('dialog1');
dialog.querySelector('.count').addEventListener('click', function() {
count += 1;
dialog.close();
document.getElementById('result').innerHTML = "Result Clicked on Count+1 = " + count;
});
function showdialog() {
dialog.showModal();
dialog.querySelector('.close').addEventListener('click', function() {
dialog.close();
});
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<body>
<div id='result'>Result = 0</div>
<button id="show-dialog" type="button" class="mdl-button" onclick='showdialog()'>Show Dialog</button>
<dialog class="mdl-dialog" id='dialog1'>
<h4 class="mdl-dialog__title">Allow data collection?</h4>
<div class="mdl-dialog__content">
<p>
Allowing us to collect data will let us get you the information you want faster.
</p>
</div>
<div class="mdl-dialog__actions">
<button type="button" class="mdl-button count">Count +1</button>
<button type="button" class="mdl-button close">Close</button>
</div>
</dialog>
</body>