You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多表单页面根据提交表单设置Cookie的实现问题

多表单提交时正确设置Cookie的解决方案

核心问题分析

你当前代码的问题在于:

  1. 点击按钮时传入的是所有表单的集合,而putCookie函数固定取集合里的第一个表单(form[0]),所以不管点哪个按钮,都只会用第一个表单的值。
  2. 过期时间计算有错误:today.getTime(Nickname)是无效写法,getTime()不需要参数。
  3. 多个元素重复使用相同ID(nameBox、submit),违反HTML规范。

修复步骤

  • 每个按钮点击时,传入当前按钮所属的表单,用this.form即可直接获取。
  • 修改putCookie函数,直接使用传入的表单对象,不再用索引[0]。
  • 修正过期时间的计算逻辑。
  • 移除重复ID(或改为唯一ID)。

修改后的完整代码

<html>
<head>
    <script>
        var today = new Date();
        // 修正getTime()的错误参数,计算30天后的过期时间
        var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000);

        function setCookie(name, value) {
            document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
        }

        function putCookie(form) {
            // 直接使用传入的当前表单,不再固定取第一个
            setCookie("userName", form.usrname.value);
            return true;
        }
    </script>
</head>
<body>
<form id="forma1">
    <!-- 移除重复ID,或改为唯一ID如nameBox1 -->
    <input type="text" value="Enter Your Nickname" name='usrname'>
    <!-- 点击时传入当前表单:this.form -->
    <input type="button" value="Go!" onclick="putCookie(this.form);"> 
</form>
<form id="forma2">
    <input type="text" value="Enter Your Nickname" name='usrname'>
    <input type="button" value="Go!" onclick="putCookie(this.form);">
</form>
<form id="forma3">
    <input type="text" value="Enter Your Nickname" name='usrname'>
    <input type="button" value="Go!" onclick="putCookie(this.form);">
</form>
</body>
</html>

额外说明

  • this.form是DOM元素的内置属性,按钮作为表单的子元素,通过它可以直接获取到所属的表单对象,无需通过ID或标签名查找。
  • escape()用于对Cookie值进行编码,避免特殊字符导致的问题;如果需要更现代的编码方式,也可以使用encodeURIComponent()。

内容的提问来源于stack exchange,提问作者Ricky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:05:29