JavaScript&活动 - 最佳实践 [英] JavaScript & Events - Best Practice

查看:145
本文介绍了JavaScript&活动 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经读过以下编码技术被认为是错误的:

I once read that the following coding technique is considered bad:

<a HREF="page.htm" onClick="alert('Hello World')">text link</a>

基本上,在HTML标记中使用这些事件处理程序(如onClick)是错误的使用方法。这是什么原因?什么是这种坏技术?执行此操作的正确方法是什么?

Basically, having these event handlers (like onClick) within the HTML tag is the wrong approach to use. What is the reason for this? What is this "bad" technique called? What is the "proper" way to do this?

推荐答案

这是内联事件处理程序属性 。 (+1 chjj对替代品的回答)。由于多种原因,它通常被认为是糟糕:

This is an inline event handler attribute. (+1 chjj's answer for alternatives). It's generally considered ‘bad’ for a number of reasons:


  • 您将小部分JavaScript语法与HTML语法内联:

  • you're mixing small pieces of JavaScript syntax inline with HTML syntax:


  • 当你有很多这些,特别是当你有很多元素都包含基本相同的代码时,它更难以阅读和维护代码;

  • when you have lots of these, especially when you have lots of elements that all contain essentially the same bit of code, it's harder to read and maintain the code;

当您需要在代码中使用特殊到HTML字符时,您会遇到嵌套转义错误:

you get nested-escaping horrors when you need to use special-to-HTML characters in your code:

例如:

<a href="x.html" onclick="this.innerHTML= '&lt;em>I like &quot;fish &amp;amp; chips&quot;&lt;/em>';">




  • 目标元素和所有祖先的属性节点成为变量,可能隐藏自己的同名变量。有关这种令人惊讶且几乎总是不受欢迎的行为的背景,请参见此问题;

    • properties of the target element and all ancestor nodes become variables, potentially hiding your own variables of the same name. See this question for background on this surprising and almost always unwanted behaviour;


      • 由于浏览器具有不同的DOM属性,这引入了怪异的不兼容性;

      • this introduces spooky incompatibilities as browsers have different DOM properties;

      未来的浏览器引入新属性可能会破坏您的代码。

      and future browsers introducing new properties will potentially break your code.

      这篇关于JavaScript&amp;活动 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆