📜  HTML 中的属性和属性有什么区别?

📅  最后修改于: 2021-09-14 01:36:32             🧑  作者: Mango

HTML是用于创建要在 Web 浏览器上显示的文档的标准语言。在 JavaScript 中执行 DOM 对象操作时,经常会与属性和属性混淆。在了解差异之前,让我们首先定义文档对象模型。

DOM:它是文档对象模型的首字母缩写词。当浏览器解析您的 HTML 代码时,它会创建一个相应的 DOM 节点。从此节点对象访问 HTML 属性。

简单来说,DOM 是 HTML 的 API,我们使用 JavaScript 等语言或 React、Vue.js 等框架使用相应的 DOM 对象访问和操作 HTML。

笔记:

  1. 一些DOM属性不具备相应的属性。
  2. 一些 HTML 属性不具有相应的属性。
  3. 一些 HTML 属性,如“class”,拥有到属性的 1:1 映射。

让我们看一些快速示例来演示属性和属性之间的差异。

示例:考虑以下 HTML 代码片段。

html


 

    
 
    

          


html


 

 
     

        Click the button the display         the number of attributes         associated with it.     

                       

          


javascript
var Attrdemo = document.getElementById(
    'AtrributeDemo').attributes[1].name;


javascript


 

 
     

        Click the "display" button for         the number of attributes         associated with it.     

               

          


html


 

 
     

        Click the button the display the         current className & the edited         className     

                       

      

              


输出:

现在,让我们考虑用户输入“1234”,那么element.getAttribute(“value”)将返回“Phone Number:”,因为我们提供了它作为该属性的初始值。但是element.value将返回“1234”。

因此, value 属性具有开发人员在 HTML 源代码中提供的初始文本内容,因为 value 属性反映了输入框内的当前文本内容(在这种情况下由用户提供)。

现在我们对差异有了基本的了解,让我们深入了解并了解更多差异。

属性:属性由 HTML 定义,用于自定义标签。

html



 

 
     

        Click the button the display         the number of attributes         associated with it.     

                       

          

输出为 2,因为这两个属性是: id=”AttributeDemo”onclick=”myFunction()”。

注意: document.getElementsById(‘AttributeDemo’).attributes代码片段返回指定节点属性的集合,作为 NamedNodeMap 对象。要访问节点,我们可以使用通用索引方法。替换上面代码片段中的以下行。

javascript

var Attrdemo = document.getElementById(
    'AtrributeDemo').attributes[1].name;

输出:

onclick

属性的数据类型为字符串。所以无论属性的值如何,它都会返回一个字符串。
例子:

document.getElementById('AtrributeDemo').getAttribute('id')

输出:

AttributeDemo

属性:与在 HTML 中定义的属性不同,属性属于 DOM。由于 DOM 是 JavaScript 中的对象,因此我们可以获取和设置属性。

javascript



 

 
     

        Click the "display" button for         the number of attributes         associated with it.     

               

          

输出:

当相应的属性更改时,默认属性(非用户定义的)也会更改,反之亦然。

html



 

 
     

        Click the button the display the         current className & the edited         className     

                       

      

              

输出:

笔记:

  1. 非自定义属性(如 id、class 等)具有到属性的 1:1 映射。
  2. 我们使用“className”来访问(获取或设置)“class”属性,因为“class”是 JavaScript 中的保留关键字。
  3. 当相应的属性更改时,具有定义的默认值的属性保持不变。

HTML 属性和 DOM 属性的区别:

Attribute Property
Attributes are defined by HTML. Properties are defined by the DOM.
The value of an attribute is constant. The value of a property is variable.
These are used to initialize the DOM properties. After initialization, the job is finish. 
 
No such job defined.