当我想在某个事件被触发后阻止其他事件处理程序执行时,我可以使用两种技术之一.我将在示例中使用jQuery,但这也适用于plain-JS:
event.preventDefault()$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
return false$('a').click(function () {
// custom handling here
return false;
});
Run Code Online (Sandbox Code Playgroud)
这两种停止事件传播的方法之间有什么显着差异吗?
对我来说,return false;比执行方法更简单,更短并且可能更不容易出错.使用该方法,您必须记住正确的套管,括号等.
另外,我必须在回调中定义第一个参数才能调用该方法.也许,有一些原因可以解释为什么我应该避免这样做并使用preventDefault呢?有什么更好的方法?
javascript jquery event-handling event-propagation dom-events
我正在使用"Closure Compiler",在编译脚本时我会花费以下内容:
编译之前:
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print,print_input_delimiter
// ==/ClosureCompiler==
var myObj1 = (function() {
var undefined; //<----- declare undefined
this.test = function(value, arg1) {
var exp = 0;
arg1 = arg1 == undefined ? true : arg1; //<----- use declare undefined
exp = (arg1) ? value * 5 : value * 10;
return exp;
};
return this;
}).call({});
var myObj2 = (function() {
this.test = function(value, arg1) {
var exp = …Run Code Online (Sandbox Code Playgroud)