在现代JavaScript应用程序中使用DOM Level 0的最佳实践 [英] Best practice for using DOM Level 0 in modern JavaScript applications

查看:85
本文介绍了在现代JavaScript应用程序中使用DOM Level 0的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于使用 DOM Level 0收藏品是否有一套商定的最佳做法在现代JavaScript应用程序中? ( document.forms document.images 等。)

Is there an agreed set of "best practices" for use of the DOM Level 0 collections in modern JavaScript applications? (document.forms, document.images, etc.)

在使用jQuery的应用程序中,我注意到使用 $(...)更改下拉列表内容的倾向.html()切换基础节点,而不是使用 element.options [] 。这是因为最好避免使用DOM 0集合,还是因为jQuery使更改底层DOM结构变得更容易?

In applications using jQuery, I've noticed a tendency to, say, change the contents of a drop-down using $(...).html() to switch out the underlying nodes, rather than using element.options[]. Is this because the DOM 0 collections are best avoided, or because jQuery makes it much easier to change the underlying DOM structure?

编辑: I猜测部分问题包括旧功能是否可靠跨浏览器。我记得,曾经有一段时间,IE会自动将< tbody> 标签添加到你的桌面,而firefox则不会。这使得走在dom tree痛苦的跨浏览器。同样, element.options [] 更改集合中的选项时出现问题。这些人是否可靠跨浏览器?

I guess part of the question includes if the older features are reliable cross-browser. I remember that, once upon a time, IE would add <tbody> tags automatically to your table, while firefox would not. That made walking the dom tree painful cross-browser. Similarly, element.options[] had problems when changing the options in the collection. Are these guys reliable cross-browser?

推荐答案

首先,很棒的问题。

DOM Level 0-1功能是我最喜欢的工具箱。支持是巨大的。我将重点介绍以下DOM级别0的每个子集的优缺点:

DOM Level 0-1 functionality is my favorite toolbox to work with. The support is tremendous. I'll highlight the pros and cons for each subset of DOM Level 0 below:

由于这些是作为 ElementNode 的属性添加的,因此您只能拥有一个处理程序。对于某些情况(例如:事件委托),这是繁重的。但是,我觉得DOM足够多(特别是当你的项目变大时)为DOM 0级处理程序提供足够的空间。没有库/框架来平滑旧浏览器,DOM Level 2监听器很难实现。即使作为Flash开发人员(在任何地方都使用了侦听器),DOM 0事件对我来说也容易得多。其中一个亮点是为您设置了值(没有IE浏览器和其他模型咳嗽)。例如,考虑这个标记:

Since these are added as properties of an ElementNode, you can only have one handler. For some instances (eg: event delegation), this is burdensome. However, I feel that the DOM is diverse enough (especially as your project gets bigger) to have enough room for DOM level 0 handlers. DOM Level 2 listeners are painful to implement without a library/framework to smooth over older browsers. Even as a Flash developer (listeners are used everywhere), the DOM 0 events are far easier to me. One of the highlights is the fact that the this value is set for you (without IE hacking and coughing like the other model). For example, consider this markup:

< div id =foo> Cick Me!< / div>

现在,所有需要做的就是选择和附加DOM Level 0处理程序。

Now, all that needs to be done is selection and attachment of a DOM Level 0 handler.

var foo = document.getElementById("foo");
function bar()
{
    console.log(this); //<div id="foo">
}
foo.onclick = bar;

这是选择元素的一种非常简单的方法,也是 Event.currentTarget ;

That's a very easy way of selecting elements and an alternative to Event.currentTarget;

这里有关于DOM Level 0事件与DOM Level 2事件的精彩讨论:[链接]

There's a great discussion on DOM Level 0 events vs. DOM Level 2 events here: [link]

Bar none, HTMLCollections 是我最喜欢的DOM功能。因为为你选择了节点,所以不需要运行查询。在我看来,它们是今天最容易被忽视的DOM功能。名称遍历如: collection [name] 是非常方便,在遍历表格时肯定有帮助。例如,考虑这一点标记:

Bar none, HTMLCollections are my favorite feature of the DOM. Because nodes are selected for you, there's no need to run queries. In my opinion, they're the most overlooked DOM feature today. Name traversal such as: collection["name"] is very handy and certainly helps when traversing forms. For example, consider this bit of markup:

<form action="./" id="foo" name="foo" method="post" onsubmit="return false;">
    <fieldset>
        <legend>Dummy Form</legend>
        <input type="text" name="bar">
        <select name="baz">
            <option selected value="1">1</option>
        </select>
    </fieldset>
</form>

有很多DOM Level 0方法可以解决这个问题。

There are many DOM Level 0 ways to tackle this.


  1. var foo = document.forms.foo; //< form id =fooonsubmit =return false; method =postname =fooaction =./>

演示: http://jsbin.com/udozoz/0edit#preview

var foo = document.forms [0]; //< form id =fooonsubmit =return false; method =postname =fooaction =./>

演示: http://jsbin.com/udozoz/2/edit#preview

var foo = document.getElementById(foo); //< form id =fooonsubmit =return false; method =postname =fooaction =./>

演示: http://jsbin.com/udozoz/3/edit#preview

当然,方法3更为可取。它是DOM级别1,而不是DOM级别0.但是,名称遍历自然适合 HTMLFormElement.elements HTMLCollection 。由于您应该在表单元素上使用 name 属性,因此您可以轻松访问它们而无需 id 属性。

Certainly, method 3 is more preferable. It's DOM Level 1, and not DOM Level 0. However, name traversal fits naturally for the HTMLFormElement.elements HTMLCollection. Since you're supposed to use name attributes on form elements, you can easily access them without an id attribute.

Ex: var baz = foo.elements.baz;

当使用共享相同名称的单选按钮(一次只能选择一个)时,可以使用 HTMLFormElement.elements HTMLCollection 以选择全部单选按钮。这非常强大。考虑这个标记:

When using radio buttons that share the same name (to make only one selectable at a time), you can use the HTMLFormElement.elements HTMLCollection to select all of the radio buttons. That's very powerful. Consider this markup:

<form action="./" id="foo" name="foo" method="post" onsubmit="return false;">
    <fieldset>
        <legend>Radio Buttons</legend>
        <label for="select_1">1</label>
        <input id="select_1" type="radio" name="selectable" value="a">
        <label for="select_2">2</label>
        <input id="select_2" type="radio" name="selectable" value="b">
        <label for="select_3">3</label>
        <input id="select_3" type="radio" name="selectable" value="c">
    </fieldset>
</form>

你可以使用这个简单的代码并让每个单选按钮带有 name selectable的属性值:

You could use this simple code and have every radio button with the name attribute value of "selectable":


var foo = document.forms.foo;
var selectables = foo.elements.selectable;
console.log(selectables); //[input#select_1 a, input#select_2 b, input#select_3 c]

演示:< a href =http://jsbin.com/upiyom/edit#preview =noreferrer> http://jsbin.com/upiyom/edit#preview

var foo = document.forms.foo;
var selectables = foo.selectable;
console.log(selectables); //[input#select_1 a, input#select_2 b, input#select_3 c]

演示:< a href =http://jsbin.com/upiyom/2/edit#preview =noreferrer> http://jsbin.com/upiyom/2/edit#preview

选项2使您可以绕过元素 HTMLCollection 完全。虽然肯定不如选项1那么明确,但它仍然在今天使用。

Option 2 enables you to bypass the elements HTMLCollection completely. While certainly not as clear as Option 1, it's still used today.

HTMLCollections 自DOM引入以来变得更加人性化和更加多样化等级0.例如,查看可用于表的 HTMLCollections 。这令人震惊。有一个 HTMLTableElement.rows HTMLTableElement.tBodies HTMLTableSectionElement(thead,tbody,tfoot).rows HTMLTableRowElement.cells 。这些集合非常强大,并且使用表格允许DOM遍历更简单(允许您使用它们)。

HTMLCollections have become more populous and far more diverse since the introduction of DOM Level 0. For example, take a look at the HTMLCollections available for a table. It's staggering. There's HTMLTableElement.rows, HTMLTableElement.tBodies, HTMLTableSectionElement (thead, tbody, tfoot).rows, and HTMLTableRowElement.cells. Those collections are very powerful, and have made DOM traversal far simpler with tables (permitting you use them).

虽然 ElementNodes 上的属性在DOM级别0中并不像现在那样多样化,但仍然有几个宝石注意:

While the properties on ElementNodes weren't as diverse in DOM Level 0 as they are now, there's still a couple of gems to note:

HTMLInputElement.defaultChecked

defaultChecked 使您可以绕过搜索 HTMLInputElement 已选中属性,因为它存储了基于该属性的布尔值值。这意味着您不必通过与get / set / removeAttribute相关的IE构建的草率解决方案进行克服。稍后,还会添加 defaultValue 属性以满足类似需求。

defaultChecked enables you to bypass searching through an HTMLInputElement's checked attribute completely because it stores a boolean based on that attribute's value. This means you don't have to kludge through sloppy solutions for IE builds related to get/set/removeAttribute. Later on, the defaultValue property would also be added to fill a similar need.

document.lastModified [非标准]

lastModified 将存储文档上次更改的时间。这是一个很酷的小功能,使用有限。

lastModified will store the last time the document was changed. It's a cool little feature that has limited use.

HTMLDocument.title

title 将为您抓取文档的标题。它的用法充其量只是一个小利基。

title will snag the document's title for you. Its usage is a small niche at best.

关于你的 tbody 问题,今天的浏览器确实添加了 HTMLTableSectionElement (tbody),如果您不推广正确的DOM结构。您应该知道正确的表格标记,以便将来不会出现问题:)。

In regards to your tbody question, browsers today do add an HTMLTableSectionElement (tbody) if you don't to promote proper DOM structure. You should get to know proper table markup so this won't be a problem in the future :).

示例标记:

错误:

<table>
    <!-- tbody will be inserted here and will wrap the tr -->
    <tr>
        <td>Hello, World!</tr>
    </tr>
</table>

正确:

<table>
    <tbody>
        <tr>
            <td>Hello, World!</td>
        </tr>
    </tbody>
</table>

演示: http://jsbin.com/exomub/edit#preview

需要回家的主要观点是DOM级别0的大部分都是在DOM级别1和2中标准化的。这意味着浏览器支持很广泛(因为它是真的很老)。除了旧浏览器版本中的一些边缘情况之外,不应该过多担心使用它。在一天结束时,这是你的选择。

The main point that needs to be driven home is that most of DOM Level 0 is standardized in DOM Levels 1 and 2. This means the browser support is extensive (since it's really old). There shouldn't be too much apprehension to using it—aside from some edge cases in older browser builds. At the end of the day, it's your choice.

我想补充一点,我过去只是非常简短地用来开发HTML / JavaScript的。我这是一个爱好,所以我不知道关于浏览器/项目出错的恐怖故事。

I'd like to add that I've only very briefly—in the past—been employed to develop with HTML/JavaScript. I do it as a hobby, so I'm not privy to "horror stories" about browsers/projects gone wrong.

我希望这清除了一些事情。

I hope this cleared a few things up.

-Matt

ElementNode - 带<的节点code> nodeType == 1

HTMLCollection - 直播阵列 - 比如浏览器收集的NodeList

HTMLCollection - Live array-like NodeList collected by the browser

这篇关于在现代JavaScript应用程序中使用DOM Level 0的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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