表单存储(form storage)
优质
小牛编辑
133浏览
2023-12-01
Framework7 可以很方便存储和解析表单的数据,特别是在 Ajax 加载的页面。并且,当你再次加载相同的页面之后,Framework7 可以自动帮你填充上次的内容!
启用表单自动存储
要启用表单自动存储功能,只需要:
- 在表单上增加一个 "store-data" class
- 在表单上增加一个 id 属性。如果没有 id, 无法正常工作的。
- 确保你的input都有 "name" 属性,没有name属性的input将会被忽略
不需要任何JS代码就可以实现表单自动存储
<!-- Form has additional "store-data" class to enable form storage on this form -->
<form id="my-form" class="list-block store-data">
<ul>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">Name</div>
<div class="item-input">
<!-- Make sure that input have "name attrobute" -->
<input type="text" name="name" placeholder="Your name">
</div>
</div>
</div>
</li>
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">E-mail</div>
<div class="item-input">
<!-- Make sure that input have "name attrobute" -->
<input type="email" name="email" placeholder="E-mail">
</div>
</div>
</div>
</li>
... other form fields ...
</ul>
</form>
JS API
这是怎么实现的?其实非常简单,Framework7 会在表单有任何改动的时候调用 formToJSON,然后在"pageInit" 事件触发时调用 formFromJSON。
所有的表单数据都存储在 localStorage 中,每一个表单都有一个自己的key,key的规则是:localStorage.f7form-[formID]
,其中 [formId] 就是表单的 id 属性。每一个这样的key都包含了一个表单的所有数据。
下面是一些管理表单数据的可用的方法
myApp.formGetData(formId) - 获取id对应的表单的数据
- formId - 字符串 - form 的id
- 返回一个JSON数据
myApp.formDeleteData(formId) - 删除id对应的表单数据
- formId - 字符串 - form 对应的id
myApp.formStoreData(formId, formJSON) - store formJSON data for form with formId "id" attribute
myApp.formStoreData(formId, formJSON) - 把一个JSON数据存储到一个表单对应的localStorage中
- formId - 字符串 - 表单的id属性
- formJSON - 对象 - 要存储的JSON对象
<form id="my-form2" class="list-block store-data">
... form fields ...
</form>
<div class="content-block">
<p><a href="#" class="button get-storage-data">Get Data</a></p>
<p><a href="#" class="button delete-storage-data">Delete Data</a></p>
<p><a href="#" class="button save-storage-data">Save Data</a></p>
</div>
var myApp = new Framework7();
var $$ = Dom7;
$$('.get-storage-data').on('click', function() {
var storedData = myApp.formGetData('my-form2');
if(storedData) {
alert(JSON.stringify(storedData));
}
else {
alert('There is no stored data for this form yet. Try to change any field')
}
});
$$('.delete-storage-data').on('click', function() {
var storedData = myApp.formDeleteData('my-form2');
alert('Form data deleted')
});
$$('.save-storage-data').on('click', function() {
var storedData = myApp.formStoreData('my-form2', {
'name': 'John',
'email': 'john@doe.com',
'gender': 'female',
'switch': ['yes'],
'slider': 10
});
alert('Form data replaced, refresh browser to see changes')
});
Form storage JavaScript Events
Event | Target | Description |
---|---|---|
formFromJSON | Form element | Event will be triggered after formFromJSON method called on form to fill form fields |
formToJSON | Form element | Event will be triggered after formToJSON method called on form to convert form fields to JSON |