javascript 将 div 文本分配给变量然后显示它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16575235/
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
Assign div text to variable then show it
提问by Jake
I have a simple task I'm trying to accomplish learning JavaScript but haven't been able to find a clear answer. Here's the code;
我有一个简单的任务,我正在尝试完成 JavaScript 的学习,但还没有找到明确的答案。这是代码;
<script type="text/javascript">
var show = document.getElementById("box");
document.write(show);
</script>
<div id="box">Testing</div>
Basically I want the text in the box div to be stored into a variable. Then, I want to display that variable's text on a different part of the page. With the code above I get a null error.
基本上我希望将框 div 中的文本存储到一个变量中。然后,我想在页面的不同部分显示该变量的文本。使用上面的代码,我得到一个空错误。
Thanks.
谢谢。
回答by Timidfriendly
http://jsfiddle.net/David_Knowles/LTfyH/
http://jsfiddle.net/David_Knowles/LTfyH/
<script>
var show = document.getElementById("box").innerHTML;
document.write(show);
</script>
回答by VisioN
First of all, your JavaScript should find the element you address. Hence you need to put your <script>
tag afterthe element is defined (this is one easy way).
首先,您的 JavaScript 应该找到您寻址的元素。因此,您需要在定义元素之后放置<script>
标签(这是一种简单的方法)。
Next, using .getElementById()
you can find element, but to get inner HTML out of it, you need to target .innerHTML
property:
接下来,使用.getElementById()
您可以找到元素,但要从中获取内部 HTML,您需要定位.innerHTML
属性:
<div id="box">Testing</div>
<script type="text/javascript">
var element = document.getElementById("box"),
value = element.innerHTML;
console.log(value);
</script>
Finally, for testing purposes you'd better use console. To make your script output values to the console, use console.log()
.
最后,出于测试目的,您最好使用控制台。要使您的脚本输出值到控制台,请使用console.log()
.
回答by Gindi Bar Yahav
What you're doing is storing the DOM Objectin the variable, not the text.
You should access the innerHTML
property to access the text.
您正在做的是将DOM 对象存储在变量中,而不是文本中。您应该访问该innerHTML
属性以访问文本。
var t = document.getElementById("foo").innerHTML;
t = t.trim(); // to remove the whitespaces before and after the div.
document.write(t);