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

如何实现表单Input元素携带前一页点击的指定商品名称?

跨页面传递商品名称到表单输入框的实现方案

首先纠正你写的代码里的两个错误:

  • 变量赋值要用单等号=,双等号==是用来做相等判断的,不能用来赋值
  • 方法名写错了,没有getElementByName这个API,单个元素可以用document.querySelector('h3'),多个元素用document.querySelectorAll('h3')。正确获取单个h3标签文本的写法示例:
var productName = document.querySelector('h3').textContent.trim();

下面给你两种可行的实现方案:

方案一:通过URL参数传递(最常用)

商品列表页代码

给每个商品的购买按钮或卡片绑定点击事件,把商品名称作为参数拼到表单页的URL里:

// 假设每个商品项有类名product-item,购买按钮类名buy-btn
document.querySelectorAll('.buy-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    // 获取当前商品的名称
    const productName = this.closest('.product-item').querySelector('h3').textContent.trim();
    // 编码处理特殊字符,避免URL出错
    const encodedName = encodeURIComponent(productName);
    // 跳转到表单页并带上参数
    window.location.href = `form.html?product=${encodedName}`;
  });
});

表单页代码

页面加载时读取URL参数,填充到指定输入框:

window.addEventListener('DOMContentLoaded', function() {
  // 解析URL参数
  const urlParams = new URLSearchParams(window.location.search);
  const productName = urlParams.get('product');
  // 解码还原原始名称
  const decodedName = decodeURIComponent(productName);
  // 找到目标输入框(假设输入框id为product-name)
  const inputBox = document.getElementById('product-name');
  if (inputBox && decodedName) {
    inputBox.value = decodedName;
    // 可选:设置输入框为只读,防止用户修改
    inputBox.readOnly = true;
  }
});

方案二:使用localStorage存储(适合不想暴露参数在URL的场景)

商品列表页代码

点击购买时把商品名称存入localStorage,再跳转表单页:

document.querySelectorAll('.buy-btn').forEach(btn => {
  btn.addEventListener('click', function() {
    const productName = this.closest('.product-item').querySelector('h3').textContent.trim();
    // 将商品名称存入本地存储
    localStorage.setItem('selectedProduct', productName);
    // 跳转到表单页
    window.location.href = 'form.html';
  });
});

表单页代码

页面加载时读取localStorage里的内容,填充输入框后建议清除存储,避免影响后续操作:

window.addEventListener('DOMContentLoaded', function() {
  const productName = localStorage.getItem('selectedProduct');
  const inputBox = document.getElementById('product-name');
  if (inputBox && productName) {
    inputBox.value = productName;
    inputBox.readOnly = true;
    // 清除存储,防止下次打开表单页还显示旧数据
    localStorage.removeItem('selectedProduct');
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:01:46