为什么HTML DOM属性也应该反映到HTML DOM属性中?

[英]Why should HTML DOM properties be reflected into HTML DOM attributes as well?


It's said by this article that one of the important reasons for HTML properties to be reflected back to the DOM is because CSS selectors rely on attributes, but why's that? This could be done without the reflection based on the spec.

这篇文章说,HTML属性反映回DOM的一个重要原因是CSS选择器依赖于属性,但为什么呢?这可以在没有基于规范的反射的情况下完成。

For people who don't know what I'm talking about, read below:

对于那些不知道我在说什么的人,请阅读以下内容:

In browsers, CSS selectors rely on attributes to work.

在浏览器中,CSS选择器依赖于属性来工作。

#myButton[someAttribute] {
  opacity: 0.5; 
  font-weight: bold
}

So in our JavaScript if we change the property of an element, eventually we have to reflect it to the HTML DOM as well like this:

所以在我们的JavaScript中,如果我们更改元素的属性,最终我们必须将它反映到HTML DOM,如下所示:

// we have changed some property
myButton.someAttribute= true; 

// but this is not adequate, we need to reflect as well
myButton.setAttribute('someAttribute', '');

so we get this:

所以我们得到这个:

<button id="myButton" someAttribute></button>

not this non-reflected button:

不是这个非反射按钮:

<button id="myButton"></button>

7 个解决方案

#1


8  

Not all DOM properties map to attributes. The ones that do reflect to and from attributes, do so to maintain parity with the document language — in this case, HTML, which only has a concept of attributes, which as you've correctly pointed out is relied on by Selectors.

并非所有DOM属性都映射到属性。确实反映到属性和来自属性的那些,这样做是为了保持与文档语言的一致性 - 在这种情况下,HTML只有一个属性的概念,正如你正确指出的那样,选择器依赖它。

If attribute selectors mapped directly to DOM properties without the DOM discriminating between attribute properties and other kinds of properties, then attribute selectors such as the following would match, even though none of these exist as attributes in HTML:

如果属性选择器直接映射到DOM属性而DOM不区分属性属性和其他类型的属性,那么属性选择器(如下所示)将匹配,即使这些属性在HTML中都不存在:

[classList]
[className]
[dataset]
[offsetLeft]
[offsetTop]
[offsetWidth]
[offsetHeight]

... as well as [someAttribute] matching elements with your non-existent someAttribute as a property even when you don't reflect it with setAttribute().

...以及[someAttribute]匹配元素与您不存在的someAttribute作为属性,即使您没有使用setAttribute()反映它。

In fact, this is exactly why label[htmlFor] incorrectly matches label[for] elements in Internet Explorer 7, even though the for attribute in HTML is simply called for, not htmlFor — the DOM uses htmlFor to make up for the fact that for is a reserved word in many languages including JavaScript, the main DOM scripting language, preventing it from being used as a property ident.

事实上,这正是标签[htmlFor]错误地匹配Internet Explorer 7中标签[for]元素的原因,即使HTML中的for属性只是被调用,而不是htmlFor - DOM使用htmlFor来弥补以下事实:是许多语言中的保留字,包括JavaScript,主要的DOM脚本语言,阻止它被用作属性标识。

#2


6  

DOM attributes and properties are not equivalent, but they're related.

DOM属性和属性不等同,但它们是相关的。

Attributes are intended to be used to initialize DOM properties. When the HTML is parsed, all the attributes are used to initialize the corresponding DOM properties. If you later modify an attribute with setAttribute or removeAttribute, the corresponding property is also updated (similar to reloading the HTML with the new attribute).

属性旨在用于初始化DOM属性。解析HTML时,所有属性都用于初始化相应的DOM属性。如果稍后使用setAttribute或removeAttribute修改属性,则还会更新相应的属性(类似于使用new属性重新加载HTML)。

But it doesn't go the other way. Updating a property doesn't change the corresponding attribute. This is why you can assign to the .value of an input, and see this reflected in the browser display, but when you look at the element in Developer Tools you still see the original value="whatever" attribute. In some cases this has special benefits -- when you click on the Reset button of a form, it resets all the value properties from their value attributes.

但它不会走另一条路。更新属性不会更改相应的属性。这就是为什么你可以分配输入的.value,并在浏览器显示中看到这一点,但是当你在Developer Tools中查看元素时,你仍然可以看到原始值=“whatever”属性。在某些情况下,这有一些特殊的好处 - 当您单击表单的“重置”按钮时,它会从其值属性中重置所有值属性。

#3


6  

IMHO; Some attributes have a 1:1 mapping with their respective properties in the DOM. The reflection is automatically made for common attributes like id. You can also define your own attributes (your HTML will be considered invalid, but you can use the doctype to validate them). My guess is that due to this uncertainty created by rogue attributes. They preferred to map only the attribute:property which has predictable behaviour and usage. You can still use your custom attributes in your css but you're in manual mode. You got to keep your s**t together and reflect them yourself. This far west(freedom) mentality is one the things that made web tech so popular and easy to use. You can do things as you see fit. I do not recommend it for maintainability reasons but you could.

恕我直言;某些属性与DOM中的各自属性具有1:1映射。自动对像id这样的常见属性进行反射。您还可以定义自己的属性(您的HTML将被视为无效,但您可以使用doctype来验证它们)。我的猜测是由于流氓属性造成的这种不确定性。他们倾向于仅映射属性:具有可预测行为和用法的属性。您仍然可以在css中使用自定义属性,但是您处于手动模式。你必须保持自己的态度并自己反思。这种遥远的西方(自由)心态是使网络技术如此受欢迎和易于使用的东西之一。你可以按照自己的意愿做事。出于可维护性的原因,我不推荐它,但你可以。

#4


5  

Your example uses a button, but the article is using the disabled property but with something other than a button. On a button, the browser will automatically reflect changes to the disabled property onto the attribute, and vice versa, but this doesn't happen with all elements. Change your example to use a div and you'll see that you'd need to manually coordinate the two if desired.

您的示例使用了一个按钮,但该文章使用了disabled属性,但使用的是按钮以外的其他属性。在一个按钮上,浏览器会自动将对disabled属性的更改反映到属性上,反之亦然,但所有元素都不会发生这种情况。更改您的示例以使用div,您将看到如果需要,您需要手动协调这两个。

Or for custom attributes, use data- attributes instead. If you delete the property from my_element.dataset, I'm pretty sure the attribute will be deleted too.

或者对于自定义属性,请改用数据属性。如果从my_element.dataset中删除该属性,我很确定该属性也将被删除。

#5


4  

This is to keep the HTML and DOM synchronized, because at some point CSS selectors will be checking the DOM element and relying on the attributes to be accurate.

这是为了保持HTML和DOM同步,因为在某些时候CSS选择器将检查DOM元素并依赖于属性是准确的。

If the DOM isn't accurate, then the CSS won't be accurate either. What if HTML didn't bother to reflect attributes back to the DOM?

如果DOM不准确,那么CSS也不准确。如果HTML没有将属性反映回DOM,该怎么办?

Let's say the text of an input field is initially black, and you want the text to be red when it is disabled. Now let's say the user did something and a function you wrote disabled the input field through javascript.

假设输入字段的文本最初是黑色的,并且您希望文本在禁用时为红色。现在让我们说用户做了一些事情,你编写的函数通过javascript禁用了输入字段。

If HTML didn't reflect that 'disabled' attribute back to the DOM, CSS would NEVER KNOW that the element was disabled.

如果HTML没有将“禁用”属性反映回DOM,那么CSS永远不会知道该元素已被禁用。

So the text color would never be changed to red. Remember, CSS checks and relies on DOM attributes. If HTML doesn't change the DOM attributes, for all CSS cares about, nothing has changed so everything will remain the same.

因此文本颜色永远不会变为红色。请记住,CSS检查并依赖于DOM属性。如果HTML没有改变DOM属性,对于所有CSS关心,没有任何改变,所以一切都将保持不变。

For a less technical analogy, let's say CSS is Batman, HTML is Gotham Police Department, an Attribute is the bat-signal, and the DOM is the sky.

对于技术性较小的类比,假设CSS是Batman,HTML是Gotham警察局,属性是蝙蝠信号,DOM是天空。

Batman(css) constantly checks the sky(dom) to see if his bat-signal light(attribute) is being shown by the Gotham Police Department(html). If there was some event(an attribute changed) which happened in Gotham where the Gotham Police Department(html) needed Batman(css) to help, but they just didn't bother to send him an update through the sky(dom) with the bat-signal(attribute update), Batman would never know there was a job that needs to be done.

蝙蝠侠(css)不断检查天空(dom),看看他的蝙蝠信号灯(属性)是否由Gotham警察局(html)显示。如果有一些事件(一个属性改变了)发生在Gotham,Gotham警察局(html)需要蝙蝠侠(css)帮助,但他们只是没有费心向他发送更新通过天空(dom)与蝙蝠信号(属性更新),蝙蝠侠永远不会知道有一项工作需要完成。

I mean he's an awesome super hero so he would eventually find out but sadly, CSS is no Batman.

我的意思是他是一个非常棒的超级英雄,所以他最终会发现但遗憾的是,CSS并不是蝙蝠侠。

#6


3  

The article speaks about custom elements, and takes the example of a <div> element with it's natural behaviour for some properties like hidden or disabled.

本文讨论了自定义元素,并以

元素为例,其中包含隐藏或禁用等属性的自然行为。

So, first of all, don't take the sentence you mention as a directive from your god, because it's not.

所以,首先,不要把你提到的句子作为你神的指示,因为事实并非如此。

Simply, if you have an application with some css using the disasbled property for specific styling, be aware that, if you want to :

简单地说,如果你有一个使用某个css的应用程序使用disasbled属性进行特定样式,请注意,如果你想:

  1. create some custom elements
  2. 创建一些自定义元素
  3. manipulate their attributes through Javascript, including disasbled
  4. 通过Javascript操纵他们的属性,包括disasbled
  5. see the css applied for disasbled property of custom elements you are manipulating
  6. 请参阅应用于您正在操作的自定义元素的disasbled属性的css

Then, yes, you'll need to reflect back to DOM

那么,是的,你需要反思DOM

#7


3  

Well, this is the first question I'm answering but I'll try either way.

嗯,这是我回答的第一个问题,但我会尝试两种方式。

To be honest, it's kinda hard to tell what you're asking but if you're looking to reflect HTMLElement property changes back on the DOM (via attributes). Then here's the code (using HTMLElement's):

说实话,很难说出你在问什么,但是如果你想要反映在DOM上的HTMLElement属性变化(通过属性)。然后这是代码(使用HTMLElement):

// Defines a new property on an Object.
Object.defineProperty(HTMLElement.prototype, "someAttribute", {
    // Configurable
    configurable: true,

    // Enumerable
    enumerable: true,

    /* Getter
        (Allows you get the value like this =>
            element.someAttribute // returns the value of "someAttribute"
        )
    */
    get: function() {
        return this.getAttribute("someAttribute")
    },

    /* Setter
        (Allows you to modify/ update the value like this => 
            element.someAttribute = "lorem ipsum"
        )
    */
    set: function(data) {
        this.setAttribute("someAttribute", data)
    }
})

Hope this answered your question.

希望这能回答你的问题。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/08/02/b275abd0794dce4449a279d1f957d392.html



 
  © 2014-2022 ITdaan.com 联系我们: