如何在 JavaScript 中使用 innerhtml?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12653292/
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-08-23 10:57:13  来源:igfitidea点击:

How can I use innerhtml in JavaScript?

javascripthtmlinnerhtml

提问by ghie

My problem is that I don't know how to show the innerhtml of my form.

我的问题是我不知道如何显示表单的innerhtml。

The form is like a survey form and once you clicked the submit button, all the contents I had answered would show like a summary page...

表单就像一个调查表,一旦你点击提交按钮,我回答的所有内容都会像一个摘要页面一样显示......

function displayResult() {
    var first = document.getElementById("first").value;

    var middle = document.getElementById("middle").value;

    var last = document.getElementById("last").value;

    alert("oh");
    var maincontent = document.getElementById("content").innerHTML;
    maincontent = "<p>" + first;

}

采纳答案by 0x499602D2

var maincontent = document.getElementById("content").innerHTML;
maincontent = "<p>" + first;

On the second line you're overwriting the variable, not setting the .innerHTML. This is what you want:

在第二行,您将覆盖变量,而不是设置.innerHTML. 这就是你想要的:

var maincontent = document.getElementById("content");
maincontent.innerHTML = "<p>" + first;

Also, you must make sure the elements with ids of "first" "middle" and "last" actually exist, or this might cause a TypeError.

此外,您必须确保 ID 为“first”、“middle”和“last”的元素确实存在,否则可能会导致TypeError.

回答by suresh.g

Try this:

尝试这个:

But , you should have id as first. and you should need content div in html part.

但是,您应该首先拥有 id。并且您应该在 html 部分需要内容 div。

<script>
function displayResult() {
    var first = document.getElementById("first").value;

    var maincontent = "";
    maincontent = "<p>" + first + "</p>";
    document.getElementById("content").innerHTML = maincontent;

}
</script>
<body>
<input type="text" id="first" value="good">
<button onclick="displayResult();">Click me!!!</button>
<div id="content"></div>
</body>

回答by Quannt

What is your element with id "contend" , a div? td? tr? or ? The way it should be is

您的 id 为 "contend" 的元素是什么,一个 div?是吗?tr?或者 ?它应该是这样的

 <div id='content'> 
   </div>

and then this is the javascript code

然后这是javascript代码

document.getElementById("content").innerHTML = "<p>" + first + middle + last + "</p>"

回答by jrajav

Instead of this:

取而代之的是:

var maincontent = document.getElementById("content").innerHTML;
maincontent = "<p>" + first;`

Try this:

尝试这个:

document.getElementById("content").innerHTML = "<p>" + first;

You may also want to use .innerHTML to get 'first', rather than .value? I'm not sure what kind of element 'first' is.

您可能还想使用 .innerHTML 来获得“first”,而不是 .value?我不确定“第一”是什么类型的元素。