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

如何用jQuery实现通过宽、高、长3个输入框筛选匹配的产品列表

实现方案

核心思路

  • 先把静态的产品列表转换为结构化的JS对象数组,存储每个产品的宽、高、长、品牌、价格参数
  • 为输入框和提交按钮添加专属ID,方便jQuery获取输入值和绑定点击事件
  • 匹配逻辑采用「三维度偏差总和最小」的规则计算匹配度:每个产品的宽、高、长与输入值的差值绝对值相加,数值越小匹配度越高
  • 点击提交后对产品做排序处理,重新渲染列表展示结果

完整实现代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<!-- 引入jQuery依赖,本地有资源可替换 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- 输入区域 -->
宽度 <input type="text" id="widthInput"><br>
长度 <input type="text" id="lengthInput"><br>
高度 <input type="text" id="heightInput"><br>
<input type="submit" id="submitBtn" value="筛选匹配产品">

<br/><br/>

<!-- 产品展示区域 -->
<h3>匹配产品列表</h3>
<div id="productList"></div>

<script>
// 结构化产品数据,可按需扩展
const products = [
  { width: 120, length: 180, height:75, brand: 'Company A', price: '$333' },
  { width: 127, length: 80, height:175, brand: 'Company A', price: '$715' },
  { width: 76, length: 280, height:75, brand: 'Company D', price: '$343' },
  { width: 220, length: 110, height:175, brand: 'Company E', price: '$133' },
  { width: 650, length: 70, height:98, brand: 'Company F', price: '$238' },
  { width: 150, length: 10, height:77, brand: 'Company S', price: '$342' },
  { width: 420, length: 5, height:122, brand: 'Company A', price: '$597' }
]

// 页面初始化时先渲染全部产品
renderProducts(products)

// 绑定提交按钮点击事件
$('#submitBtn').click(function() {
  // 获取输入值并转换为数字,空值默认设为0可按需调整逻辑
  const inputW = Number($('#widthInput').val()) || 0
  const inputL = Number($('#lengthInput').val()) || 0
  const inputH = Number($('#heightInput').val()) || 0

  // 计算每个产品的匹配偏差值,按匹配度从高到低排序
  const sortedProducts = products.map(product => {
    const deviation = Math.abs(product.width - inputW) + Math.abs(product.length - inputL) + Math.abs(product.height - inputH)
    return { ...product, deviation }
  }).sort((a, b) => a.deviation - b.deviation)

  // 重新渲染排序后的产品列表
  renderProducts(sortedProducts)
})

// 渲染产品列表的公用方法
function renderProducts(list) {
  let html = ''
  list.forEach(item => {
    html += `${item.width} X ${item.length} X ${item.height} ${item.brand} ${item.price}<br>`
  })
  $('#productList').html(html)
}
</script>
</body>
</html>

自定义调整说明

  • 如果需要仅筛选尺寸大于等于输入值的产品,可在排序前添加过滤逻辑:.filter(p => p.width >= inputW && p.length >= inputL && p.height >= inputH)
  • 如果需要给不同尺寸维度设置权重,可在计算偏差时给对应维度的差值乘以权重系数即可
  • 可按需添加输入校验逻辑,比如限制仅能输入数字、输入为空时的提示等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:54:02