防止同一个触发器函数执行两次的最好方法是什么?
What is the best way to prevent the same trigger function from executing twice?
触发器可以应用于表单级和/或项级。让它而不是再次执行的最佳方式是什么?
<form id='f'>
<input id='i' type='text' />
</form>
<script>
validate = function(e) { ... }
reformat = function(e) { ... }
document.getElementById('f').addListener('change',validate,true);
document.getElementById('i').addListener('change',validate,true);
document.getElementById('i').addListener('change',reformat,true);
</script>
上下文:数据字典说i
项需要立即验证,应用程序编写人员说表单中的所有项都应该立即验证。
这是同一个函数,通常调用一次,但有时调用两次。
防止validate
函数执行两次的最佳方法是什么?
注意:e.stopPropagation()
停止所有对click
事件的进一步调用,因此不再调用reformat
触发器。
你可以在event参数中添加一个prop来确保它只运行一次:
validate = function(e) { if (e.done) return; /* code */ e.done = true; }
document.getElementById('f').addListener('change',validate,true);
document.getElementById('i').addListener('change',validate,true);
<标题> 演示虽然我不明白你为什么要绑定两次事件
编辑:对于跨浏览器(读:IE)更改为:
validate = function(e) {
if ((e = e || window.event).done) return;
/* code */
e.done = true;
}
document.getElementById('f').addListener('change',validate,true);
document.getElementById('i').addListener('change',validate,true);
<标题>编辑演示 标题>标题>基本思路(基于http://www.quirksmode.org/js/events_order.html):
function cancelBubbling(e) {
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
var validate = function(e) {
cancelBubbling(e); // important!
...
};
相关文章:
- Meteor Router数据函数被调用两次
- 从MySQL数据库中获取输入数据需要两次页面刷新
- Module.start()已激发两次
- jQuery 方法调用了两次
- 为什么 POST 方法将表单数据发送到服务器两次
- 在AngularJS中,一次进行两次调用是一种可接受的方法
- 有没有一种不那么黑客的方法可以防止我的 on('click') 触发两次
- 使用两次点击方法
- C 节点本机扩展调用方法两次
- 如何在rails3ajax表单中两次使用jQuery-submit方法
- 为什么是动能.形状'的drawFunc方法调用了两次
- 必须点击两次做一个方法在React
- iframe在设置src属性时调用Action方法两次
- $scope's方法通过ng-click调用:由IE执行两次
- 方法调用两次在第二次运行- JavaScript
- 防止同一个触发器函数执行两次的最好方法是什么?
- 使用T3JS框架时,最好的方法是两次使用相同的模块
- 当两次调用一个方法时,仅呈现一个SVG组件
- window.open两次不起作用(第二个窗口没有出现)-Blocker解决方法
- 方法的一部分调用了两次