javascript - 为什么将值返回到innerHTML 时,函数内部的innerHTML 会被忽略?

标签 javascript html

我正在调用一个打印到 div 的函数,然后返回一个也打印到 div 的字符串。以下只会打印“二”,但我希望它先打印“一”,然后打印“二”:

<body>
     <div id="view"></div>
</body>
<script>
global_cdiv = "view"
function test1(){
    document.getElementById(global_cdiv).innerHTML += "one" + "<br>";
    return "two";
}
document.getElementById(global_cdiv).innerHTML += test1();

</script>

调试中没有出现任何错误或任何内容。 为什么Javascript会忽略函数内的innerHTML? (解决方法是将 test1() 中的值存储到变量中然后打印它,但为什么不能直接使用 test1 ?)

最佳答案

document.getElementById(global_cdiv).innerHTML += test1();

的缩写形式
document.getElementById(global_cdiv).innerHTML = document.getElementById(global_cdiv).innerHTML + test1();

评估之前test1() innerHTML值被评估为空并且与 test1() 的结果连接起来这是 two 。所以,实际的表达就变成了这样

document.getElementById(global_cdiv).innerHTML = "" + "two";

这会覆盖 test1() 中设置的任何内容。这就是为什么你只看到 two .

要了解它确实会覆盖它,请更改您的 test1()像这样

function test1(){
    document.getElementById(global_cdiv).innerHTML += "one" + "<br>";
    console.log(document.getElementById(global_cdiv).innerHTML);
    return "two";
}

它将打印 one<br>

关于javascript - 为什么将值返回到innerHTML 时,函数内部的innerHTML 会被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19604888/

相关文章:

javascript - onBlur 在 React 下拉组件中不起作用

html - 使 div 中的 span 水平滚动

python - 将现有的 defaultdict 输出为适当的 JSON 格式以用于 flare 树状图?

html - 如何在没有单独的单元格样式的情况下设置 html 表格列的宽度?

html - 溢出自动在 Firefox 中不起作用它在 Chrome 中运行良好

javascript - Ng-show 没有正确过滤

javascript - 处理循环数组请求错误的问题

javascript - Google Maps V3 在确切位置上重叠标记

javascript - 使用jquery获取多个选择框的值

javascript - 如何合并ajax请求和ajax响应?