document.write()vs插入DOM节点:保存表单信息? [英] document.write() vs inserting DOM nodes: preserve form information?

查看:134
本文介绍了document.write()vs插入DOM节点:保存表单信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < body> 
< script>
document.writeln('< textarea>< / textarea>')
< / script>
< / body>

 <身体GT; 
< script>
var t = document.createElement('textarea');
document.body.appendChild(t);
< / script>
< / body>

(把它们看作更大的一部分,textareas 从JavaScript生成,不能被硬编码到页面中)。他们都产出相同的产出,但前者被认为是不好的,而后者则被认为是正确的做法。另一方面,如果你在页面中输入一些东西,然后刷新它,或者去其他地方,然后点击返回,那么在前一种情况下,你在textarea中输入的内容会被保留下来,而在之后它会丢失。 (至少在Firefox上)。

有没有办法使用后一种方法,仍然有用户输入到窗体中的有用功能,他们不小心点击刷新或者通过后退按钮回来(至少在Firefox上)? 我相信document.write版本实际上吹走了页面上的现有内容。也就是说,身体和脚本标签将不再存在。这就是为什么人们通常使用appendChild。



保持文本或不是浏览器特定的。我不敢打赌Firefox在未来的版本中也不会改变它的行为。当用户试图离开页面导航并且在编辑字段中存在未保存的内容时,我会建议实现一个警告对话框。通常你会用unload事件来做这件事。


Consider two web pages with the following in their body respectively:

<body>
<script>
document.writeln('<textarea></textarea>')
</script>
</body>

and

<body>
<script>
var t = document.createElement('textarea');
document.body.appendChild(t);
</script>
</body>

(think of them as part of something larger, where the textareas have to be generated from JavaScript and can't be hard-coded into the page). They both produce the same output, but the former is considered "bad", while the latter is considered the "right" way to do it. (Right?)

On the other hand, if you type something in the page and then either refresh it, or go somewhere else and hit Back, then in the former case, what you typed in the textarea is preserved, while in the later it is lost. (At least on Firefox.)

Is there a way to use the latter method and still have the useful feature that what the user has typed into a form is saved even if they accidentally hit refresh or come back via the Back button (at least on Firefox)?

解决方案

I believe the document.write version actually blows away an existing content on the page. Ie, the body and script tags will no longer be there. That is why people usually use appendChild.

Keeping the text or not is very browser specific. I wouldn't bet that Firefox would not change it's behavior on that in a future version, either. I would suggest implementing an alert dialog when the user trys to navigate away from the page and there is unsaved content in edit fields. Usually you would do this with an unload event.

这篇关于document.write()vs插入DOM节点:保存表单信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆