设置innerHTML:为什么它不会更新DOM?

发布于 2024-12-17 09:19:00 字数 1643 浏览 1 评论 0原文

想知道为什么我在重新分配变量时无法使用 document.getElementById("my_div").innerHTML 来更新 DOM。例如:

<div id="my_div" onclick="clicky();">
    Bye.
</div>
<script type="text/javascript" charset="utf-8">
    function clicky() {
        var myDivValue = document.getElementById("my_div").innerHTML;
        myDivValue = "Hello";
        console.log(myDivValue);
    }
</script>

在日志中,我可以看到单击时变量被重新分配,但 my_div 的innerHTML 保持不变。这是为什么呢?


**After several years more experience...**

对于那些刚刚开始(像我一样)并发现自己问同样的事情的人来说,有两个重要的概念需要理解:

  1. 按引用分配:我的错误是我认为 var myDivValue = element.innerHTML 将创建一个对innerHTML的引用/地址,每次我为该引用分配一个新值时,我都可以只更新内容,但这不是它的工作原理。
  2. 按值分配:相反,我只是复制了 element.innerHTML 值(空白)并将该值分配给 myDivValue,然后在 myDivValue = "Hello"; 中,我为 myDivValue 分配了一个新值,所以它当然永远不会更新 element.innerHTML

令人困惑的部分:在 JS 中使用赋值运算符 (=) 时,并不明确您是在分配引用还是值(var referenceName = reference_to_thing 与 < code>var containerName = newValue),

正如许多人在答案中所说,正确的方法是将 document.getElementById("my_div") 元素分配给myDiv

var myDiv = document.getElementById("my_div")

现在我有了一个名为 myDiv引用,我可以随时更新 innerHTML 属性我喜欢:

myDiv.innerHTML = "Hello" // innerHTML is now "Hello"
myDiv.innerHTML = "Goodbye" // Changed it to "Goodbye"

Wondering why I can't get document.getElementById("my_div").innerHTML to update the DOM when I re-assign the variable. For example:

<div id="my_div" onclick="clicky();">
    Bye.
</div>
<script type="text/javascript" charset="utf-8">
    function clicky() {
        var myDivValue = document.getElementById("my_div").innerHTML;
        myDivValue = "Hello";
        console.log(myDivValue);
    }
</script>

In the log I can see the variable get re-assigned when I click, but the innerHTML of my_div remains unchanged. Why is this?

**After several years more experience...**

For those just starting out (like I was) and found yourself asking the same thing, there are two important concepts that need to be understood:

  1. Assign by reference: My mistake was that I thought var myDivValue = element.innerHTML would create a reference/address to innerHTML and every time I assigned a new value to that reference, I could just update content, but that's not how it works.
  2. Assign by value: Instead, I was simply making a copy of element.innerHTML value (which was blank) and assigning the value to myDivValue, then in myDivValue = "Hello";, I was assigning a new value to myDivValue, so of course it would never update element.innerHTML.

The confusing part: when using the assignment operator (=) in JS, it's not explicit that you're either assigning a reference or value (var referenceName = reference_to_thing vs. var containerName = newValue),

As many have said in the answers, the right way to do this is to assign the document.getElementById("my_div") element to myDiv:

var myDiv = document.getElementById("my_div")

And now that I have a reference to the element called myDiv, I can update the innerHTML property whenever I like:

myDiv.innerHTML = "Hello" // innerHTML is now "Hello"
myDiv.innerHTML = "Goodbye" // Changed it to "Goodbye"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

冬天的雪花 2024-12-24 09:19:00

innerHTML 计算结果为字符串。我不确定为什么你会期待不同的事情。考虑一下:

var a = 'foo'; // now a = 'foo'
var b = a; // now a = 'foo', b = 'foo'
b = 'bar'; // now a = 'foo', b = 'bar'

重新分配 b 不会改变 a

编辑添加:如果上面的内容不清楚,如果您想更改innerHTML,您可以直接分配给它:

document.getElementById("my_div").innerHTML = "Hello";

您不需要,并且可以不使用中间变量。

innerHTML evaluates to a string. I'm not sure why you would expect anything different. Consider this:

var a = 'foo'; // now a = 'foo'
var b = a; // now a = 'foo', b = 'foo'
b = 'bar'; // now a = 'foo', b = 'bar'

Re-assigning b doesn't change a.

Edited to add: In case it's not clear from the above, if you want to change innerHTML, you can just assign to it directly:

document.getElementById("my_div").innerHTML = "Hello";

You don't need, and can't use, an intermediary variable.

可可 2024-12-24 09:19:00
 var myDivValue = document.getElementById("my_div").innerHTML;

存储innerHTML的值,innerHTML包含一个字符串值,而不是一个对象。所以不可能引用 elem 。您必须直接存储对象才能修改其属性。

var myDiVElem = document.getElementById("my_div");
myDiVElem.innerHTML = 'Hello'; // this makes the change
 var myDivValue = document.getElementById("my_div").innerHTML;

stores the value of innerHTML, innerHTML contains a string value, not an object. So no reference to the elem is possible. You must to store directly the object to modify its properties.

var myDiVElem = document.getElementById("my_div");
myDiVElem.innerHTML = 'Hello'; // this makes the change
踏雪无痕 2024-12-24 09:19:00

对于仍在苦苦挣扎的人们,请确保您的财产拼写正确。
因为它是 innerHTML 而不是 innerHtml。太容易搞错了!

For people still struggling, make sure you're spelling the property right.
As it is innerHTML and not innerHtml. It's so easy to get it wrong!

转瞬即逝 2024-12-24 09:19:00

对于未来的谷歌用户来说,我的问题是我正在调用复数元素。

document.getElementsByClassName('class').innerHTML

因此它返回一个数组而不是单个元素。我把它改成了单数。

document.getElementByClassName('class').innerHTML

这样我就可以更新innerHTML 值了。

For future googlers my problem was that I was calling the plural elements.

document.getElementsByClassName(‘class’).innerHTML

So it returned an Array not a single element. I changed it to the singular.

document.getElementByClassName(‘class’).innerHTML

That made it so I could update the innerHTML value.

ˇ宁静的妩媚 2024-12-24 09:19:00

刚刚浪费了几个小时,我还可以补充一点,不要意外地拥有两个具有相同 ID 的元素,这一点至关重要

And having just wasted a couple of hours, I can also add that its critical not to accidentally have two elements with the same ID

苦行僧 2024-12-24 09:19:00

你应该像这样设置innerHTML值

 var myDivValue = document.getElementById("my_div").innerHTML = "Hello";

you should set the innerHTML value like

 var myDivValue = document.getElementById("my_div").innerHTML = "Hello";
静谧幽蓝 2024-12-24 09:19:00

设置innerHTML/outerHTML后需要重新分配元素:

let indexInParent=[].slice.call(elem.parentElement.children).indexOf(elem);
elem.innerHTML=innerHTML;
elem=elem.parentElement.children[indexInParent];

you need to reassign the element after setting innerHTML/outerHTML:

let indexInParent=[].slice.call(elem.parentElement.children).indexOf(elem);
elem.innerHTML=innerHTML;
elem=elem.parentElement.children[indexInParent];
哆兒滾 2024-12-24 09:19:00

我有同样的问题(设置innerHTML:为什么它不会更新DOM?)但对于我的情况,这是一个不同的问题。我的问题原来是使用“InnerHtml”而不是“InnerHTML”。令人沮丧的是,js 会让你在没有任何警告的情况下继续运行它。例如下面的代码,点击后没有错误,控制台日志将显示innerHtml已成功修改。但在 html 页面上,你看到它仍然说“再见”。

<div id="my_div" onclick="clicky();">
    Bye.
</div>

<script type="text/javascript" charset="utf-8">
  function clicky() {
    document.getElementById("my_div").innerHtml="<div>Hello</div>";
    console.log(document.getElementById("my_div").innerHtml);
  }
</script>

I had the same question (Setting innerHTML: Why won't it update the DOM?) but for my case, it's a different issue. My issue turned out to be using "InnerHtml" instead of "InnerHTML". The frustrating thing is that js would let you go ahead and run it without any warning whatsoever. For example with this code below, after click there's no error and console log will show that innerHtml got modified successfully. But yet on the html page, you see it still says "Bye".

<div id="my_div" onclick="clicky();">
    Bye.
</div>

<script type="text/javascript" charset="utf-8">
  function clicky() {
    document.getElementById("my_div").innerHtml="<div>Hello</div>";
    console.log(document.getElementById("my_div").innerHtml);
  }
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文