我正在try 捕获表单的提交按钮按下操作,如果表单已提交,页面将刷新,并显示几个隐藏字段.我想捕获表单是否以前提交过,如果它在重新加载时提交,我想取消隐藏的字段.我试图使用全局变量来实现这一点,但是我无法使其正常工作.

Here is what I tried:

  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
    }
  });

Any suggestions on what is wrong with this code?

推荐答案

As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.

有几种方法可以将值存储在另一个地方,以便在加载时使用JavaScript对其进行初始化


Query string

When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:

<form method="GET">
    <input type="hidden" name="clicked" value="true" />
    <input type="submit" />
</form>

初始加载页面时,未设置任何查询字符串.提交此表单时,输入的namevalue组合在查询字符串中作为clicked=true传递.因此,当页面再次加载该查询字符串时,可以判断按钮是否被单击.

要读取此数据,可以在页面加载时使用以下脚本:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var clicked = getParameterByName('clicked');

(Source)

Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.

In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters


Web Storage

随着HTML5的引入,我们还获得了Web Storage,它允许您跨页面加载在浏览器中保存信息.有localStorage个可以保存较长时间的数据(只要用户不手动清除它)和sessionStorage,它只在当前浏览会话期间保存数据.后者在这里对您很有用,因为您不想在用户稍后返回时将"clked"设置为true.

Here I set the storage on the button click event, but you could also bind it to form submit or anything else.

$('input[type="submit"][value="Search"]').click(function() {
    sessionStorage.setItem('clicked', 'true');
});

Then when you load the page, you can check if it's set using this:

var clicked = sessionStorage.getItem('clicked');

Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:

sessionStorage.removeItem('clicked');

If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.

//set
localStorage.setItem('myObject', JSON.stringify(myObject));

//get
var myObject = JSON.parse(localStorage.getItem('myObject'));

Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.


Cookies

An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.

You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.

$('input[type="submit"][value="Search"]').click(function() {
    $.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});

Then on page load you can read the cookie like this:

var clicked = $.cookie('clicked');

在你的 case 中,由于cookie会在不同的会话中持续存在,你需要在完成任何需要处理的操作后立即将其取消设置.你不希望用户一天后回来,仍然将clicked设置为true.

if(clicked === "true") {
    //doYourStuff();
    $.cookie('clicked', null);
}

(a non-jQuery way to set/read cookies can be found right here)

I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.


window.name

Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:

window.name = "my value"

它只能存储字符串,所以如果您想保存一个对象,您必须将其字符串化为字符串,就像上面的localStorage个示例一样:

window.name = JSON.stringify({ clicked: true });

主要区别在于,这些信息不仅会在页面刷新中保留,还会在不同的域中保留.但是,它仅限于您当前所在的选项卡.

This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.

Jquery相关问答推荐

从克隆的输入中读取数据属性,返回初始输入的值

jQuery .append() 创建两个元素而不是一个

JQuery - 从先前 Select 的下拉列表中隐藏/显示选项

获取 html 元素的 onclick 事件的 data-* 属性

如何使用 jQuery 以编程方式触发对链接的点击?

ASP .NET MVC 在每个字段级别禁用客户端验证

子元素点击事件触发父点击事件

模态窗口中的 Twitter Bootstrap Datepicker

如何使用 jQuery 为文本对齐动态添加样式

如何使用 Javascript/jQuery 确定图像是否已加载?

通过 AJAX 和 jQuery 使用 HTML5 文件上传

自动完成将值而不是标签应用于文本框

我想了解 jQuery 插件语法

我如何知道 jQuery 是否有待处理的 Ajax 请求?

jQuery确定匹配的类是否具有给定的ID

变量首字母大写

使用 jQuery 获取鼠标单击图像的 X/Y 坐标

如何使用 jQuery 或仅使用 Javascript 将按钮重定向到另一个页面

粘性侧边栏:向下滚动时固定在底部,向上滚动时固定在顶部

jquery - 成功时使用ajax结果返回值