简体   繁体   English

document.getElementById不会获取新输入的HTML文本输入值

[英]document.getElementById doesn't get newly entered HTML text input value

I use the following code. 我使用以下代码。

The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1". 想法是使用名称“ PrintThis”打印div的内容,该名称包含文本输入区域“ textarea1”。

The problem is that getElementById only ever returns the string loaded with the page; 问题在于,getElementById仅返回页面加载的字符串。 "cake" in this case. 在这种情况下为“蛋糕”。

If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie". 如果通过单击并在页面上键入“ textarea1”将“ cake”更改为“ pie”,则printContents仍然具有“ cake”而不是“ pie”。

<html> 
<head> </head> 
<script type="text/javascript">

function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
 <body> 
  <div id="printThis" name="printThis">
   <textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
  </div>

  <input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>

In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options. 在生产版本中,我还使用AJAX将文本区域值发布回服务器,因此理论上可以使用页面刷新,尽管该页面没有运行,但我尝试使用这些选项。

document.location.reload(true);
window.top.location=window.top.location;

The production version does have jQuery available too. 生产版本也有可用的jQuery。

first of all you are trying to get innerHTML of the div, instead of the actual textarea. 首先,您尝试获取div的innerHTML,而不是实际的textarea。 secondly instead of trying to get innerHTML try using value. 其次,与其尝试获取innerHTML,不如尝试使用值。

http://jsfiddle.net/qdymvjz8/ http://jsfiddle.net/qdymvjz8/

<div id="printThis" name="printThis">
   <textarea id="textarea1" cols="1" rows="10">cake</textarea>
  </div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">

function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}

If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values. 如果生产中的div中有多个项目,则可以遍历div的子级并拖出值。

function printFunction(divName) {
  var printContents = document.getElementById(divName),
    childItemCount = 0,
    stringToPrint = '';

 for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
    stringToPrint += printContents.children[childItemCount].value;
 }

 console.log(stringToPrint);
 //Now call a script to print (not included)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM