為什么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 联系我们: