javascript 为什么我得到 [object HTMLParagraphElement]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16147488/
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
Why did I get [object HTMLParagraphElement]
提问by hsming
I am a newbie. Here is my code:
我是新手。这是我的代码:
<html>
<head>
<script type="text/javascript">
function replyOne () {
document.getElementById("comment_content").value = document.getElementById("username")
}
</script>
</head>
<body>
<p id="username">Hyman</p>
<textarea id="comment_content" ></textarea>
<button onclick="replyOne()">Copy Text</button>
</body>
</html>
I expect that when I click the button, it will copy 'Hyman' to the textarea. But instead it just writes '[object HTMLParagraphElement]'.
我希望当我单击按钮时,它会将“Hyman”复制到文本区域。但它只是写了'[object HTMLParagraphElement]'。
回答by Doorknob
It should be:
它应该是:
document.getElementById("comment_content").value =
document.getElementById("username").innerHTML
Without the .innerHTML
, it will try to copy in the actual element, not its content.
如果没有.innerHTML
,它将尝试复制实际元素,而不是其内容。
回答by Ruju
You can use textContent,innertext,innerHTML.But two of them are browser specific and innerHTML can work on three major browser.
您可以使用 textContent、innertext、innerHTML。但其中两个是特定于浏览器的,innerHTML 可以在三个主要浏览器上工作。
Also you can parse the dom by parent children combination and will get required value.
您也可以通过父子组合解析 dom 并获得所需的值。
function replyOne () {
document.getElementById("comment_content").value=document.getElementById("username").innerHTML;
//OR
document.getElementById("comment_content").value=document.getElementById("username").textContent;
}