首页 > 解决方案 > 捕获整个文档,包括动态文本区域值

问题描述

我有一份打印出记录行的报告。我可以在此报告中添加和删除行,也可以编辑每一列。

问题是在保存文档时,我在单击事件中使用波纹管。
var htmlText = "<html>" + $("html").html() + "</html>";

除了动态添加的行之外,这对所有内容都适用。Row 存在,但输入的文本textareas不存在。

为什么不抓取这些信息?

标签: jqueryhtml

解决方案


只要用户更改了任何输入,浏览器就不会将 textarea 中的值更新回 DOM,这同样适用于输入和选择。因此,一种解决方法是在保存 HTML 文件之前自己将更改应用到 DOM 中。

$("#insert").on("click", function() {
  $("<textarea />").appendTo($("#htmlBody")).val("This is a dynamic textarea");
  $("<input type=\"text\" value=\"\" />").appendTo($("#htmlBody")).val("This is a dynamic input");
});

$("#save").on("click", function() {
  alert($("#htmlBody").html());
});

$("#saveTextarea").on("click", function() {
  $("textarea").each(function(index, item) { $(item).text($(item).val()); })
  $("input").each(function(index, item) { $(item).attr("value", $(item).val()); })
  alert($("#htmlBody").html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="htmlBody">
  <textarea>This is a textarea</textarea>
  <input type="text" value="This is an input" />
</div>
<button id="insert">Insert Textarea</button>
<button id="save">Save</button>
<button id="saveTextarea">Save With Textarea Value</button>


推荐阅读