无。
在一个元素的属性中绑定事件,实际上就创建了一个内联事件处理函数(如<h1 onclick="alert(this);"...>...</h1>),内联事件处理函数有其特殊的作用域链,并且各浏览器的实现细节也有差异。
如果在元素的内联事件处理函数中使用的变量或调用的方法不当,将导致脚本运行出错。
| 所有浏览器 |
|---|
与其他函数不同,内联事件处理函数的作用域链从头部开始依次是:调用对象、该元素的 DOM 对象、该元素所属 FORM 的 DOM 对象(如果有)、document 对象、window 对象(全局对象)。
如以下代码:
<form action="." method="get"><input type="button" value="compatMode" onclick="alert(compatMode);"></form>
相当于1:
<form action="." method="get"><input type="button" value="compatMode"></form><script>document.getElementsByTagName("input")[0].onclick=function(){with(document){with(this2.form)3{with(this2){alert(compatMode);}}}}</script>以上两种写法的代码在所有浏览器中都将弹出 document.compatMode 的值。
将上述代码中的 "compatMode" 替换为 "method",则在各浏览器中都将弹出 "get",即 INPUT 元素所在表单对象的 method 属性值。
注:
1. 这段代码仅为说明问题而模拟各浏览器的行为,并非表示所有浏览器都是如此实现的。
2. 是使用 this 关键字还是直接使用这个 DOM 对象,在各浏览器中有差异,详情请看本文 2.1 中的内容。
3. 是否添加 FORM 对象到作用域链中,各浏览器在实现上也有差异,详情请看本文 2.2 中的内容。
参考 WebKit 的源码:
void V8LazyEventListener::prepareListenerObject(ScriptExecutionContext* context){if (hasExistingListenerObject())return;v8::HandleScope handleScope;V8Proxy* proxy = V8Proxy::retrieve(context);if (!proxy)return;// Use the outer scope to hold context.v8::Local<v8::Context> v8Context = worldContext().adjustedContext(proxy);// Bail out if we cannot get the context.if (v8Context.IsEmpty())return;v8::Context::Scope scope(v8Context);// FIXME: cache the wrapper function.// Nodes other than the document object, when executing inline event handlers push document, form, and the target node on the scope chain.// We do this by using "with" statement.// See chrome/fast/forms/form-action.html// chrome/fast/forms/selected-index-value.html// base/fast/overflow/onscroll-layer-self-destruct.html//// Don"t use new lines so that lines in the modified handler// have the same numbers as in the original code.String code = "(function (evt) {" "with (this.ownerDocument ? this.ownerDocument : {}) {" "with (this.form ? this.form : {}) {" "with (this) {" "return (function(evt){";code.append(m_code);// Insert "
" otherwise //-style comments could break the handler.code.append( "
}).call(this, evt);}}}})");v8::Handle<v8::String> codeExternalString = v8ExternalString(code);v8::Handle<v8::Script> script = V8Proxy::compileScript(codeExternalString, m_sourceURL, m_lineNumber);if (!script.IsEmpty()) {v8::Local<v8::Value> value = proxy->runScript(script, false);if (!value.IsEmpty()) {ASSERT(value->IsFunction());v8::Local<v8::Function> wrappedFunction = v8::Local<v8::Function>::Cast(value);// Change the toString function on the wrapper function to avoid it// returning the source for the actual wrapper function. Instead it// returns source for a clean wrapper function with the event// argument wrapping the event source code. The reason for this is// that some web sites use toString on event functions and eval the// source returned (sometimes a RegExp is applied as well) for some// other use. That fails miserably if the actual wrapper source is// returned.DEFINE_STATIC_LOCAL(v8::Persistent<v8::FunctionTemplate>, toStringTemplate, ());if (toStringTemplate.IsEmpty())toStringTemplate = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New(V8LazyEventListenerToString));v8::Local<v8::Function> toStringFunction;if (!toStringTemplate.IsEmpty())toStringFunction = toStringTemplate->GetFunction();if (!toStringFunction.IsEmpty()) {String toStringResult = "function ";toStringResult.append(m_functionName);toStringResult.append("(");toStringResult.append(m_isSVGEvent ? "evt" : "event");toStringResult.append(") {
");toStringResult.append(m_code);toStringResult.append("
}");wrappedFunction->SetHiddenValue(V8HiddenPropertyName::toStringString(), v8ExternalString(toStringResult));wrappedFunction->Set(v8::String::New("toString"), toStringFunction);}wrappedFunction->SetName(v8::String::New(fromWebCoreString(m_functionName), m_functionName.length()));setListenerObject(wrappedFunction);}}}从以上代码可以看出,WebKit 在向作用域链中添加对象时,使用了 "this" 关键字,并且通过判断 "this.form" 是否存在来决定是否添加 FORM 对象到作用域链中。
其他浏览器中也有类似的实现方式,但在各浏览器中,将目标对象(即绑定了此内联事件处理函数的对象)添加到作用域链中的方式有差异,判断并决定是否在作用域链中添加 FORM 对象的方法也不相同。
各浏览器都会将内联事件处理函数所属的元素的 DOM 对象加入到作用域链中,但加入的方式却是不同的。
如以下代码:
<input type="button" value="hello" onclick="alert(value);">
在所有浏览器中,都将弹出 "hello"。
再修改代码以变更 INPUT 元素的内联事件处理函数的执行上下文:
<input type="button" value="hello" onclick="alert(value);"><script>var $target=document.getElementsByTagName("input")[0];var o={onclick:$target.onclick,value:"Hi, I"m here!"};o.onclick();</script>在各浏览器中运行的结果如下:
| IE Chrome | Hi, I"m here! |
|---|---|
| Firefox Safari Opera | hello |
可见,各浏览器将内联事件处理函数所属的元素的 DOM 对象加入到作用域链中的方式是不同的。
在 IE Chrome 中的添加方式类似以下代码:
<input type="button" value="hello"><script>var $target=document.getElementsByTagName("input")[0];$target.onclick=function(){with(document){with(this){alert(value);}}}</script>而在 Firefox Safari Opera 中的添加方式则类似以下代码:
<input type="button" value="hello"><script>var $target=document.getElementsByTagName("input")[0];$target.onclick=function(){with(document){with($target){alert(value);}}}</script>由于极少需要改变内联事件处理函数的执行上下文,这个差异造成的影响并不多见。
各浏览器都会将内联事件处理函数所属的 FORM 对象加入到作用域链中,但如何判断该元素是否“属于”一个表单对象,各浏览器的处理方式则不相同。
如以下代码:
<form action="." method="get"><div><span onclick="alert(method);">click</span></div></form><script>document.method="document.method";</script>
在各浏览器中,点击 SPAN 元素后弹出的信息如下:
| IE Safari Opera | get |
|---|---|
| Chrome Firefox | document.method |
可见:
如果将以上代码中的 SPAN 元素更换为 INPUT 元素或其他表单元素,则在所有浏览器中的表现将一致。
当一个内联事件处理函数中访问的变量意外的与该函数作用域链中非全局对象(window)的其他对象的属性重名,将导致该变量的实际值不是预期值。
假设有以下代码:
<button onclick="onsearch()"> click here </button><script>function onsearch(){alert("Click!");}</script>作者本意为点击按钮即弹出“Click!”信息,但 WebKit 引擎浏览器的 HTMLElement 对象都有一个名为 onsearch 的事件监听器,这将导致上述代码在 Chrome Safari 中不能按照预期执行。本例中由于该监听器未定义(为 null),因此将报 “Uncaught TypeError: object is not a function” 的错误。
附:在上述代码中,追加以下代码确认 "onsearch" 的位置:
<script>var o=document.getElementsByTagName("button")[0];if("onsearch" in o)alert("当前对象有 onsearch 属性。");if(o.hasOwnProperty("onsearch"))alert("onsearch 属性是当前对象私有。");</script>
假设有以下代码:
<form action="xxx" method="get">...<a href="#" onclick="submit();">click</a></form>
作者本意为点击 A 元素后调用 FORM 的 "submit" 方法,但 Chrome Firefox 并未将 FORM 对象加入到该内联事件处理函数的作用域链中,因此以上代码在 Chrome Firefox 中并不能正常运行。
1. 尽量不要使用内联事件处理函数,使用 DOM 标准的事件注册方式为该元素注册事件处理函数,如:
<button> click here </button><script>function onsearch(){alert("Click!");}function bind($target,eventName,onEvent){$target.addEventListener?$target.addEventListener(eventName,onEvent,false):$target.attachEvent("on"+eventName,onEvent);}bind(document.getElementsByTagName("button")[0],"click",onsearch);</script>2. 必须使用内联事件处理函数时,要保证该函数内试图访问的变量是位于全局作用域内的,而不会因该函数独特的作用域链而引用到非预期的对象。最简单的办法是使用前缀,如 "my_onsearch"。