制作粘性 JavaScript
我有一个 javascript 表单,我使用 innerHTML 来设置一些文本。
当表单提交时,信息就会丢失。无论如何我可以让它“粘性”。我正在考虑一个cookie,但这就是我所知道的全部。
谢谢
<form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
简单的例子我正在捕获名称并需要 div 在表单提交后显示名称。
I have a javascript form where I am using innerHTML to set some text.
When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.
Thanks
<form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
Quick example I am capturing the name and need the div to show the name after the form submits.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将需要以某种方式保留数据。有多种选择:
localStorage[key] = value
并使用检索表单数据来存储表单数据localStorage[key]
。使用 HTML5 的本地存储为您提供了一种自我封装的方法,无需服务器端配置:
You will need to persist the data somehow. There are several options:
localStorage[key] = value
and retrieving it withlocalStorage[key]
.Using HTML5's local storage gives you a self-encapsulated approach that requires no server-side configuration:
您是否将输入标签的“值”属性设置为某些内容或空白?您可以删除(删除属性本身),以便使用最后设置的值(仅适用于非密码类型输入。此外,还没有在所有浏览器中尝试过。)。
或者更好的是,您可以使用服务器端脚本(例如 PHP、ASP、RUBY 等)将属性值设置为之前提交的值。
由于您要使用 cookie,因此仅在 js 中执行此操作要复杂得多且不可靠。
PS:我假设您没有使用 XHR(AJAX) 来提交表单,因为 XHR 不会刷新页面或重新初始化输入,除非您告诉他们这样做。
Are you setting the "value" attribute of the input tags to something or blank? you can just remove (remove the attribute itself) that so that the last value set will be used (true only for non-password type inputs. also, haven't tried it in all browsers.).
Or better yet, you can use serverside script like (PHP, ASP, RUBY, etc) to set the attribute value to the previously submitted.
doing it in js only is much more complicated and unreliable since your going to use cookies.
PS: I'm assuming your not using XHR(AJAX) to submit your forms since XHR's don't refresh pages or re-initializes inputs unless you told them to.
这应该发生在服务器端。 Javascript 用于增强页面,不依赖它来进行数据操作。
你的脚本,转换为 PHP,看起来像
......并且它每次都会工作,而无需调用任何 JS。
无论如何,您都必须以某种方式处理表单数据 - 您打算如何在没有服务器端脚本的情况下检索数据?
This should be happening server-side. Javascript is for enhancing a page, it's not to be depended on for data manipulation.
Your script, converted to PHP, would look like
...and it would work every time, without having to call any JS.
You'll have to handle the form data somehow anyway - how were you intending to retrieve the data without a server-side script?