为什么选择"innerHTML"JavaScript的属性不能是HTML属性? [英] Why "innerHTML" property from JavaScript can't be an HTML attribute?

查看:51
本文介绍了为什么选择"innerHTML"JavaScript的属性不能是HTML属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,通常使用JavaScript的"innerHTML"属性来更改HTML元素的HTML内容.此"innerHTML"属性用于HTML元素对象,例如( document.getElementById("demo").innerHTML = 5 + 6; )

As we all know to change HTML element's HTML content using JavaScript "innerHTML" property is commonly used. This "innerHTML" property is used on an HTML element object like(document.getElementById("demo").innerHTML = 5 + 6;)

我的疑问是为什么"innerHTML"属性不能在任何HTML元素中用作属性?

My doubt is why the "innerHTML" property can't be used as an attribute in any HTML element?

据我所知和理解,属性和属性具有相同的语义.

As per my knowledge and understanding attribute and property have the same semantic meaning.

那么,为什么下面的代码不能工作?

So, why the below code can not work?

<p id="demo" innerHTML="Jumbo"></p>

推荐答案

因为并非DOM元素上的所有JavaScript属性都等同于属性.

Because not all JavaScript properties on a DOM element equate to attributes.

.innerHTML 提供了一种获取或设置start和end标记之间内容的方法.因此,如果您想把东西放在那里,就把它放在那里:

.innerHTML provides a way to get or set the stuff that goes between the start and end tag. So if you want to put stuff there, just put it there:

<p id="demo">Jumbo</p>

编辑:要在下面回答您的问题,DOM是代码中HTML的概念性表示形式(在本例中为JavaScript),因此DOM元素是一个JavaScript对象,您可以用来访问和操作HTML元素(元素是HTML文档的一部分,以标签开头和结尾,因此< b>< span> Hello!</span></b> 包含两个元素,一个 b 元素和一个 span 元素.

To answer your questions below, the DOM is a conceptual representation of HTML in code (in this case JavaScript), so a DOM element is a JavaScript object that you can use to access and manipulate an HTML element (an element is a portion of an HTML document that starts and ends with a tag, so <b><span>Hello!</span></b> contains two elements, a b element and a span element.

要使用 .innerHTML 获取元素的内容,您要做的就是在表达式中访问它,而不是为其分配值.

To use .innerHTML to get the content of an element, all you need to do is access it in an expression instead of assigning a value to it.

示例:

var d = document.getElementById('myDiv');

console.log(d.innerHTML); // <em>Jumbo</em>

<div id="myDiv"><em>Jumbo</em></div>

这篇关于为什么选择"innerHTML"JavaScript的属性不能是HTML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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