使用javascript从div获取值:始终获取未定义
当我从div中获取值时,我遇到了这个问题:使用javascript从div获取值:始终获取未定义,javascript,html,undefined,Javascript,Html,Undefined,当我从div中获取值时,我遇到了这个问题: function sync(){ var n1 = document.getElementById('editor').value; alert(n1); var n2 = document.getElementById('news'); n2.value = n1; } id为editor的div如下所示: <div class='message' id='editor' contenteditable="t
function sync(){
var n1 = document.getElementById('editor').value;
alert(n1);
var n2 = document.getElementById('news');
n2.value = n1;
}
id为editor
的div如下所示:
<div class='message' id='editor' contenteditable="true" onkeyUp='sync()' style="color: black"></div>
<div id="mydiv"></div>
<script>document.getElementById('mydiv').value='hello';</script>
<div id="editor">all the information i want to store</div>
我做错了什么?试试这个
var n1 = document.getElementById('editor').innerHTML; // or innerText, or textContent
HTML元素和HTMLInputElements是不同的东西 中的HTMLInputElement中存在
值
属性
div
元素是HTMLElement
如果将div
更改为输入Javascript
将正常工作
选项是使用innerHTML
,如另一个答案中所述,但请注意,如果您不控制HTML,或者随着时间的推移忘记Javascript,这有时可能是HTML片段,并可能导致缺陷
仅供参考(没有
值
)我认为重要的是要注意,即使
是一个HTMLInputElement,您仍然会得到未定义,因为您的div
<div class='message' id='editor' contenteditable="true" onkeyUp='sync()' style="color: black"></div>
没有值属性,下面是具有值属性的div的示例:
<div class='message' id='editor' value='hello'></div>
但是,如其他答案中所述,即使您输入了一个值,.value仍将返回未定义的值,因为
是一个HTML元素,而不是一个HTMLInputElement
如果确实需要在div的值中存储一些信息,则可以执行以下操作:
<div class='message' id='editor' contenteditable="true" onkeyUp='sync()' style="color: black"></div>
<div id="mydiv"></div>
<script>document.getElementById('mydiv').value='hello';</script>
<div id="editor">all the information i want to store</div>
document.getElementById('mydiv')。value='hello';
加载div之后,强制将“hello”作为值
这样做的唯一原因是,如果您确实想在div的值中存储数据,但由于div是可见的,所以无法在innerHTML中存储数据
如果要在div中存储信息,请执行以下操作:
<div class='message' id='editor' contenteditable="true" onkeyUp='sync()' style="color: black"></div>
<div id="mydiv"></div>
<script>document.getElementById('mydiv').value='hello';</script>
<div id="editor">all the information i want to store</div>
我要存储的所有信息
然后
document.getElementById('editor').innerHTML
是正确的解决方案,但请记住,用户将能够看到网页上的信息。尝试使用jquery。。使用以下脚本$(“#editor”).text()我们使用document.getElementById('elementid').value代码>用于输入字段。在您的例子中,它是一个DIV,因此您应该使用innerHTML或innerTextvar n1=document.getElementById('editor').innerHTML代码>