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

如何随表单数据变化更新表单关联的数据模型?

输入字段值更新与Package实例创建问题

我的Package类定义

class Package {
  constructor(packageID, type, weight, height, description) {
    this.packageID = packageID;
    this.type = type;
    this.weight = weight;
    this.height = height;
    this.description = description;
  }
  getPackageId() {
    return this.packageId;
  }
  getType() {
    return this.type;
  }
  getWeight() {
    return this.weight;
  }
  getHeight() {
    return this.height;
  }
  getDescription() {
    return this.description;
  }/*
  setPackageId(packageId){
    this.packageId= packageId
    return packageId;
  }*/
  setType(type) {
    this.type = type;
    return type;
  }
  setWeight(weight) {
    this.weight = weight;
    return this.weight;
  }
  setHeight(height) {
    this.height = height;
    return this.height;
  }
  setDescription(description) {
    this.description = description;
    return this.description;
  }
}

监听输入变化的代码(存在问题)

let inputfieldtype = document.getElementById('selectPackageType');
let inputfieldweight = document.getElementById('floatWeight');
let inputfieldheight = document.getElementById('floatHeight');
let inputfielddescription = document.getElementById('description');

function updateValues() {
  var value = this.value;

  if (value == null) {

    console.log('value of packege is null');

  } else if (value != "" && (inputfieldtype == 'selectPackageType')) {
    type = value;
  } else if (value != "" && (inputfieldweight == 'floatWeight')) {
    weight = value;
  } else if (value != "" && (inputfieldheight == 'floatHeight')) {
    height = value;
  } else if (value != "" && (inputfielddescription == 'description')) {
    description = value;
  }
}
inputfieldweight.addEventListener('change', updateValues);
inputfieldheight.addEventListener('change', updateValues);
inputfielddescription.addEventListener('change', updateValues);
inputfieldtype.addEventListener('change', updateValues);

问题说明

当前if判断条件完全无效,因为代码里把DOM元素对象直接和字符串ID比较,对象与字符串永远不相等,导致所有else if分支都不会触发。我的目标是:判断哪个输入字段被修改,将其值保存到对应变量,最后创建Package类实例并填充所有属性值。

提交函数代码

//Create instance of package
const package = new Package();

//shoot all the values into one package
function submit() {
  if (typeof package != "undefined") {
    package.packageID = randomID;
    package.type = type;
    package.weight = weight;
    package.height = height;
    package.description = description;
    console.log(package);
  } else {
    console.log(package);
  }
}

对应的HTML代码

<form autocomplete="off">
  <div class="custom-select">
    <label for="selectPackageType">Type</label>
    <select id="selectPackageType" name="type">
      <option value="1">letter</option>
      <option value="2">package</option>
    </select>
  </div>
</form>
<div class="fancy-input">
  <label for="floatWeight">Weight</label>
  <input id="floatWeight" name="floatWeight" maxlength="8">
</div>
<div class="fancy-input">
  <label for="floatHeight">Height</label>
  <input id="floatHeight" name="floatHeight" maxlength="8">
</div>
<div class="fancy-input">
  <label for="description">Description</label>
  <input id="description" name="description">
</div>
<button onclick="submit()">Submit</button>

修复方案

问题核心

  1. 原代码错误地将DOM元素与字符串ID比较,正确做法是比较触发事件元素的id属性。
  2. 未声明type、weight等变量,易造成全局污染。
  3. Package构造函数需要传入参数,无参实例化会导致属性初始值为undefined。
  4. Package类的getPackageId方法存在拼写错误(返回this.packageId,但构造函数中是this.packageID)。

修复后的完整代码

1. 修正Package类

class Package {
  constructor(packageID, type, weight, height, description) {
    this.packageID = packageID;
    this.type = type;
    this.weight = weight;
    this.height = height;
    this.description = description;
  }
  getPackageId() {
    return this.packageID; // 修正拼写错误,与构造函数属性名一致
  }
  getType() {
    return this.type;
  }
  getWeight() {
    return this.weight;
  }
  getHeight() {
    return this.height;
  }
  getDescription() {
    return this.description;
  }
  setType(type) {
    this.type = type;
    return type;
  }
  setWeight(weight) {
    this.weight = weight;
    return this.weight;
  }
  setHeight(height) {
    this.height = height;
    return this.height;
  }
  setDescription(description) {
    this.description = description;
    return this.description;
  }
}

2. 优化输入监听与值存储逻辑

// 用对象统一存储输入值,避免全局变量污染
let packageData = {
  type: '',
  weight: '',
  height: '',
  description: ''
};

// 批量获取输入元素
const inputElements = {
  type: document.getElementById('selectPackageType'),
  weight: document.getElementById('floatWeight'),
  height: document.getElementById('floatHeight'),
  description: document.getElementById('description')
};

// 统一的更新函数
function updateValues() {
  const inputValue = this.value.trim();
  if (!inputValue) {
    console.log('当前输入值为空');
    return;
  }
  // 根据触发事件的元素ID匹配对应字段
  switch (this.id) {
    case 'selectPackageType':
      packageData.type = inputValue;
      break;
    case 'floatWeight':
      packageData.weight = inputValue;
      break;
    case 'floatHeight':
      packageData.height = inputValue;
      break;
    case 'description':
      packageData.description = inputValue;
      break;
  }
}

// 批量绑定change事件
Object.values(inputElements).forEach(element => {
  element.addEventListener('change', updateValues);
});

3. 优化提交函数

// 生成随机ID的辅助函数
function generateRandomID() {
  return Math.random().toString(36).slice(2, 10);
}

function submit() {
  const randomID = generateRandomID();
  // 用存储的输入值创建Package实例
  const newPackage = new Package(
    randomID,
    packageData.type,
    packageData.weight,
    packageData.height,
    packageData.description
  );
  console.log(newPackage);
  
  // 可选:提交后清空输入框与存储数据
  Object.values(inputElements).forEach(el => el.value = '');
  packageData = { type: '', weight: '', height: '', description: '' };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:14:59