![](/img/trans.png)
[英]Can't seem to get Element.setAttribute to work with webpack/babel
[英]Why element.setAttribute('checked', true) doesn't work?
我想做這樣的事情:
elementX.setAttribute('checked', true); // this is input type checkbox
elementY.appendChild(elementX);
渲染等一切都可以,但是在頁面上,不檢查輸入。 當我在chrome控制台中查看元素時,可以看到:
<input type="checkbox" checked="true">
我該怎么辦?
我已經嘗試過了
elementX.setAttribute('checked', true);
elementX.setAttribute('checked', 'true');
elementX.setAttribute('checked', 'checked');
我在控制台中沒有任何錯誤。
參見MDN :
已檢查
布爾值屬性,指示默認情況下(頁面加載時)是否選中此復選框。 這並不表示該復選框是否正在檢查:如果該復選框的狀態改變時,該內容屬性不反映更改。 (僅更新HTMLInputElement的選中的IDL屬性。)。
雖然設置了checked
屬性將顯示元素的序列化更改,但實際上不會選中該復選框。 為此,您必須調用設置器,例如
elementX.checked = true;
首先,@ CertainPerformance答案是我支持的答案,它是正確的!
我只是想更深入地了解IDL(接口設計語言)屬性與內容屬性之間的細微差別,以及它們是否具有反射性 。
在這種情況下,IDL屬性是元素的DOM表示形式上的JavaScript屬性。 不僅是任何屬性,而且是W3規范中預定義的屬性。 IDL示例
HTML中指定的屬性被視為內容屬性 。 這些屬性用於在渲染過程中在DOM節點上填充IDL屬性 。 可以通過幾種方法(包括getAttribute
方法)從DOM節點訪問內容屬性 ,但它們不會像IDL屬性那樣存儲在其上。 用簡單的術語來說, element.getAttribute("checked")
和element.checked
實際上是在兩個完全不同的對象中尋找checked的鍵。
那么, 反思是什么意思?
如果未更改節點,但如果更改了特定屬性,則從渲染的角度來看,DOM節點的property
及其HTML attribute
是可以互換的。
以任何方式更改id
和class
,無論是直接在DOM節點上還是使用element.setAttribute
方法在Attribute對象內,都將更改兩個值。
id
和class
是反射性 IDL屬性,因為實際上它們會監視其內容屬性的更改,反之亦然。
另外, checked
IDL屬性和value
也不具有反射性 。 當在DOM節點或Attribute Object上更改value
或checked
的屬性時,它不會更改另一個的相應屬性。
在這些屬性之外 (除了id
和class
之外,還有更多-盡管沒有反射與不反射的真實列表 -我想這是與DOM中Node的身份有關的任何屬性都會導致重新渲染) 內容屬性和DOM節點屬性未綁定在一起。 如果打算更新或獲取當前數據 ,這將使getAttribute
和setAttribute
無效,因為當前數據僅在DOM Node屬性中找到 。
以下示例說明了不同之處:
let i = document.querySelector("input"); i.addEventListener("id_change", function() { let HTML_Attribute = i.getAttribute("id"), DOM_Node_Property = i.id; console.log("HTML Attribute 'value': " + HTML_Attribute + "\\n DOM Node Property 'value': " + DOM_Node_Property); }) let n = 1; let timer = setInterval(function() { if(n > 2) clearInterval(timer); i.setAttribute("id", "newId_" + String.fromCharCode(Math.floor(Math.random() * 26) + 65)); i.dispatchEvent(new CustomEvent("id_change")); n++; }, 1000);
<input value="Hello World"/>
let i = document.querySelector("input"); i.addEventListener("input", function() { let HTML_Attribute = i.getAttribute("value"), DOM_Node_Property = i.value; console.log("HTML Attribute 'value': " + HTML_Attribute + "\\n DOM Node Property 'value': " + DOM_Node_Property); })
<input value="Hello World"/> <em><small>Type into the Box</small></em>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.