javascript 使用 innerHTML 更改 p 元素的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7088387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:56:02  来源:igfitidea点击:

changing content of p element using innerHTML

javascript

提问by adit

I have the following script:

我有以下脚本:

var before = document.getElementById('before');    
if (switchElement.value == 'single'){
    for (var i=0; i < before.length; i++) {
        if (before[i].id == "before_label") {
            before[i].innerHTML = 'Image';
            break;
        }
    }
    after.style.display = 'none';   
} 

and the HTML looks like:

和 HTML 看起来像:

<div id="before">
    <p id="before_label"> Before Image: </p>
    <input type="file" name="before"  size="40">
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000">
</div>

Was wondering why it didn't work and change the inner html to change?

想知道为什么它不起作用并更改内部 html 以进行更改?

回答by Jared Ng

To access the innerHTMLof before_label, just access it directly:

要访问innerHTMLof before_label,只需直接访问它:

document.getElementById('before_label').innerHTML = 'Image';

回答by daniel

getElementById only returns one element. You need to acces the child objects via childNodes.

getElementById 只返回一个元素。您需要通过 childNodes 访问子对象。

Try this:

试试这个:

var before = document.getElementById('before').childNodes;    
if (switchElement.value == 'single'){
    for (var i=0; i < before.length; i++) {
        if (before[i].id == "before_label") {
            before[i].innerHTML = 'Image';
            break;
        }
    }
    after.style.display = 'none';   
} 

回答by sdleihssirhc

Why the for loop? Just get the element by its id:

为什么是for循环?只需通过其 id 获取元素:

var before_label = document.getElementById('before_label');
if (switchElement.value == 'single') {
    before_label.innerHTML = 'Image';
    after.style.display = 'none';
}