在页面加载之间保留变量我正在尝试捕获我的表单的提交按钮按下,如果表单已提交,页面刷新,我会显示一些隐藏的字段。我想捕获表单是否已经提交之前,如果它是在重新加载时提交的,我想取消隐藏隐藏的字段。我试图使用全局变量来实现这一点,但是我无法使其正常工作。这是我尝试过的: var clicked = false;
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true; return true;");
if (clicked == true) {
// show hidden fields
} else {
// don't show hidden fields
}
});有关此代码有什么问题的任何建议吗?
3 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
尝试利用$.holdReady(),history
<script src="jquery.js" type="text/javascript"></script></head><body><form method="POST">
<input type="text" name="name" value="" />
<input type="submit" value="Search" />
<input type="hidden" />
<input type="hidden" /></form><script type="text/javascript">function show() {
return $("form input[type=hidden]")
.replaceWith(function(i, el) {
return "<input type=text>"
});}$.holdReady(true);
if (history.state !== null && history.state.clicked === true) {
// show hidden fields
// if `history.state.clicked === true` ,
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// don't show hidden fields
console.log(history);
}$.holdReady(false);
$(document).ready(function() {
$("input[type=submit][value=Search]")
.on("click", function(e) {
e.preventDefault();
if (history.state === null) {
// do stuff
history.pushState({"clicked":true});
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// do other stuff
};
});
});</script></body>
慕工程0101907
TA贡献1887条经验 获得超5个赞
使用localeStorage或sessionStorage似乎是最好的选择。
将clicked变量保存在globle 范围内的Intead以这种方式存储它:
if(localeStorage.getItem("clicked") === null)
localeStorage.setItem("clicked", "FALSE"); // for the first time$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");
var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";
localeStorage.setItem("clicked", clicked);
if (clicked == "TRUE") {
// show hidden fields
} else {
// don't show hidden fields
}});添加回答
举报
0/150
提交
取消
