我有一个附加到单击事件的复杂函数,该函数进行 AJAX 调用,然后在模式对话框中显示该信息。在处理 AJAX 调用时,该链接仍然处于事件状态,因此多次按下它会导致多个 AJAX 调用并显示多个对话框。我需要防止这种行为,因此在对话框显示之前多次单击链接只会导致一次 AJAX 调用并且对话框显示一次。
您可以在下面和JSFiddle处看到我的示例。 。对于本示例,AJAX 调用是通过超时来模拟的。如果您在对话框显示之前多次单击“这应该执行某些操作”链接,它将多次触发该事件,并且对话框会显示多次。
虽然我的示例使用 jQuery mobile,但我需要它通过 native JavaScript 工作,因为我的移动设备使用 jQuery mobile,而桌面设备不使用任何 jQuery。这不是我想要的,但它也是我无法控制的。
function showDialog() {
$.mobile.changePage("#dialog", {transition:"pop"});
}
function callDialog() {
setTimeout(showDialog, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.js"></script>
<link href="https://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.css" rel="stylesheet"/>
<div data-role="page" data-theme="a" id="home">
<div data-role="header" data-theme="a" align="center">
<h1>TESTING PAGE</h1>
<div data-role="navbar" data-iconpos="top">
<ul>
<li><a href="#home" data-icon="home">Home</a></li>
<li><a href="#away" data-icon="grid">Away</a></li>
</ul>
</div><!-- /navbar -->
</div>
<div data-role="content">
<p>TESTING PAGE ONE!!</p>
<ul data-role='listview' data-inset='true'>
<li><a href="#" onclick="callDialog();">This should do something.</a></li>
</ul>
</div>
<div data-role="footer" data-theme="a">
<h3>Copyright</h3>
</div>
</div>
<div data-role="page" data-theme="a" id="away">
<div data-role="header" data-theme="a" align="center">
<h1>TESTING PAGE</h1>
<div data-role="navbar" data-iconpos="top">
<ul>
<li><a href="#home" data-icon="home">Home</a></li>
<li><a href="#away" data-icon="grid">Away</a></li>
</ul>
</div><!-- /navbar -->
</div>
<div data-role="content">
<p>TESTING PAGE TWO!!</p>
</div>
<div data-role="footer" data-theme="a">
<h3>Copyright</h3>
</div>
</div>
<div data-role="dialog" id="dialog">
<div data-role="header" data-theme="d">
<h1>Dialog</h1>
</div>
<div data-role="content">
<h1>Close page?</h1>
<p>This is simply a page made to look like a </p>
<a
href="#" data-role="button" data-rel="back" data-theme="b">Sounds good</a> <a href="#" data-role="button" data-rel="back" data-theme="c">Cancel</a>
</div>
</div>
我尝试过 event.preventDefault
、删除事件监听器以及其他一些操作,但我似乎无法重新附加 onclick 事件监听器。因此,一旦对话框关闭,用户就无法重新使用该链接(如果他们选择的话)。如果可能的话,由于此对话框的呈现方式,我想尝试将其全部包装到单个函数中。
最佳答案
您可以使用标志来控制点击行为
例如
var inProgress = false;
function showDialog() {
inProgress = false;
$.mobile.changePage("#dialog", {transition:"pop"});
}
function callDialog() {
if(inProgress){
return;
}
inProgress = true;
setTimeout(showDialog, 1000);
}
演示:Fiddle
关于javascript - 如何防止 onclick 事件在异步任务完成之前多次触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804566/