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

如何将HTML表单值传入JavaScript对象构造函数?

解决方案:获取表单值并创建订单对象

没问题,这事儿其实挺 straightforward 的,我帮你拆解成几个步骤来实现:

1. 先修正HTML里的小细节

你当前的按钮onClick绑定少了括号,而且为了区分6个不同的商品表单,最好给每个按钮传个唯一的商品标识(比如这个帽子表单就传'beanie'),方便后续统一处理:

<input type="button" class="shoppingButton" value="Add to Basket" onClick="processOrder('beanie')">

2. 定义订单对象的构造函数

先写一个OrderItem构造函数,用来规范单个商品的订单数据结构:

function OrderItem(name, code, price, size, quantity) {
  this.productName = name;
  this.productCode = code;
  this.price = parseFloat(price); // 把字符串价格转成数字,方便后续计算
  this.size = size;
  this.quantity = parseInt(quantity); // 数量转成整数类型
}

3. 编写表单处理函数

写一个processOrder函数,根据传入的商品标识,自动匹配对应表单的所有字段值,然后实例化订单对象:

// 全局存一个购物篮数组,用来存储所有选中的商品
let shoppingBasket = [];

function processOrder(productId) {
  // 利用商品标识拼接元素ID,统一获取各字段值
  const name = document.getElementById(`${productId}Name`).value;
  const code = document.getElementById(`${productId}Code`).value;
  const price = document.getElementById(`${productId}Price`).value;
  const size = document.getElementById(`${productId}Size`).value;
  const quantity = document.getElementById(`${productId}Quantity`).value;

  // 创建新的订单实例
  const newOrderItem = new OrderItem(name, code, price, size, quantity);

  // 加入购物篮
  shoppingBasket.push(newOrderItem);

  // 测试用:打印购物篮内容,确认数据是否正确
  console.log('当前购物篮内容:', shoppingBasket);
  
  // 这里还可以扩展逻辑,比如更新页面上的购物篮数量显示、总价计算等
}

4. 扩展到6个商品的复用逻辑

因为你有6个商品表单,只要每个表单的元素ID都遵循这个命名规则(比如T恤表单用shirtName、shirtPrice、shirtSize等),按钮的onClick就传对应的标识(processOrder('shirt')),这个函数就能直接复用,不用写6遍重复代码。

额外小提示

  • 如果你觉得getElementById写起来麻烦,也可以用document.querySelector简化,比如document.querySelector(#${productId}Size).value,效果完全一致。
  • 要是想让代码更整洁,也可以用事件委托绑定点击事件,不用给每个按钮都写onClick属性——不过测试场景下,直接写onClick已经足够方便了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:49:57