...), inline event Handler functions have their own special scope chain, and implementation details vary from browser to browser."/> ...), inline event Handler functions have their own special scope chain, and implementation details vary from browser to browser.">
search
HomeWeb Front-endJS TutorialThe special scope of an element's inline event handler differs across browsers_javascript tips

标准参考

无。

问题描述

在一个元素的属性中绑定事件,实际上就创建了一个内联事件处理函数(如

...

),内联事件处理函数有其特殊的作用域链,并且各浏览器的实现细节也有差异。

造成的影响

如果在元素的内联事件处理函数中使用的变量或调用的方法不当,将导致脚本运行出错。

受影响的浏览器

所有浏览器

问题分析

1. 内联事件处理函数的作用域链

与其他函数不同,内联事件处理函数的作用域链从头部开始依次是:调用对象、该元素的 DOM 对象、该元素所属 FORM 的 DOM 对象(如果有)、document 对象、window 对象(全局对象)。

如以下代码:


相当于1


<script> document.getElementsByTagName("input")[0].onclick=function(){ with(document){ with(this<SUP>2.form)<SUP>3{ with(this<SUP>2){ alert(compatMode); } } } } </script>

以上两种写法的代码在所有浏览器中都将弹出 document.compatMode 的值。

将上述代码中的 'compatMode' 替换为 'method',则在各浏览器中都将弹出 'get',即 INPUT 元素所在表单对象的 method 属性值。

注:
1. 这段代码仅为说明问题而模拟各浏览器的行为,并非表示所有浏览器都是如此实现的。
2. 是使用 this 关键字还是直接使用这个 DOM 对象,在各浏览器中有差异,详情请看本文 2.1 中的内容。
3. 是否添加 FORM 对象到作用域链中,各浏览器在实现上也有差异,详情请看本文 2.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<: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.

  // <strong>Nodes other than the document object, when executing inline event handlers push document, form, and the target node on the scope chain.</strong>
  // 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 (<strong>this</strong>.ownerDocument ? <strong>this</strong>.ownerDocument : {}) {" \
      "with (<em><strong>this</strong>.form</em> ? <strong>this</strong>.form : {}) {" \
      "with (<strong>this</strong>) {" \
      "return (function(evt){";
  code.append(m_code);
  // Insert '\n' otherwise //-style comments could break the handler.
  code.append( "\n}).call(this, evt);}}}})");
  v8::Handle<:string> codeExternalString = v8ExternalString(code);
  v8::Handle<:script> script = V8Proxy::compileScript(codeExternalString, m_sourceURL, m_lineNumber);
  if (!script.IsEmpty()) {
    v8::Local<:value> value = proxy->runScript(script, false);
    if (!value.IsEmpty()) {
      ASSERT(value->IsFunction());

      v8::Local<:function> wrappedFunction = v8::Local<: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<:functiontemplate>, toStringTemplate, ());
      if (toStringTemplate.IsEmpty())
        toStringTemplate = v8::Persistent<:functiontemplate>::New(v8::FunctionTemplate::New(V8LazyEventListenerToString));
      v8::Local<: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(") {\n ");
        toStringResult.append(m_code);
        toStringResult.append("\n}");
        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);
    }
  }
}
</:function></:functiontemplate></:functiontemplate></:function></:function></:value></:script></:string></:context>

从以上代码可以看出,WebKit 在向作用域链中添加对象时,使用了 'this' 关键字,并且通过判断 'this.form' 是否存在来决定是否添加 FORM 对象到作用域链中。

其他浏览器中也有类似的实现方式,但在各浏览器中,将目标对象(即绑定了此内联事件处理函数的对象)添加到作用域链中的方式有差异,判断并决定是否在作用域链中添加 FORM 对象的方法也不相同。

2.1. 各浏览器在生成这个特殊的作用域链时添加目标对象时使用的方法不同

各浏览器都会将内联事件处理函数所属的元素的 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(<SPAN class=hl_2>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(<SPAN class=hl_3>$target){
			alert(value);
		}
	}
}
</script>

由于极少需要改变内联事件处理函数的执行上下文,这个差异造成的影响并不多见。

2.2. 各浏览器在生成这个特殊的作用域链时对于在何种情况下添加 FORM 对象有不同理解

各浏览器都会将内联事件处理函数所属的 FORM 对象加入到作用域链中,但如何判断该元素是否“属于”一个表单对象,各浏览器的处理方式则不相同。

如以下代码:


click
<script> document.method="document.method"; </script>

在各浏览器中,点击 SPAN 元素后弹出的信息如下:

IE Safari Opera get
Chrome Firefox document.method

可见:

  • IE Safari Opera 将 FORM 对象加入到了内联事件处理函数的作用域链中,是否加入 FORM 对象看起来是由这个元素是否是一个 FORM 的子孙级元素来决定的。因此在这些浏览器中,函数内的变量 'method' 最终得到的是 FORM 的 'method' 的值。
  • Chrome Firefox 没有将 FORM 对象加入到内联事件处理函数的作用域链中,判断是否加入 FORM 对象是看该函数绑定的目标对象的 'form' 属性是否存在。从上文中的 WebKit 的源码中可以看到 Chrome 正是使用了 'this.form' 来判断,只有目标元素是一个 FORM 的子孙级元素并且该目标元素是一个表单元素时,'form' 属性才会存在。本例中的 SPAN 元素并不是表单元素,因此变量 'method' 最终得到的是 'document.method' 的值。

如果将以上代码中的 SPAN 元素更换为 INPUT 元素或其他表单元素,则在所有浏览器中的表现将一致。

3. 由于内联事件处理函数的这种特殊的作用域链而产生问题的实例

3.1. 在元素的内联事件处理函数中访问的变量意外的与该该函数作用域链中非全局对象的其他对象的属性重名时出现的问题

当一个内联事件处理函数中访问的变量意外的与该函数作用域链中非全局对象(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>

3.2. 在表单内的子孙级非表单元素的内联事件处理函数中试图调用表单的属性或方法时出现的问题

假设有以下代码:


... click

作者本意为点击 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'。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function