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

如何根据表单输入的长宽值控制图片chocci.png的横竖重复展示次数

图片重复展示功能修复方案

原有代码存在的问题

  • 循环逻辑错误:for 循环终止条件写为 x*y,只要输入值为正,条件永远为真,会陷入死循环无限克隆图片
  • 缺少历史内容清空逻辑:多次点击提交按钮时,之前生成的图片不会被清除,会持续累加
  • 输入校验不完善:仅限制了最大值为10,未对小于1的数值、非数字输入做校验
  • 缺少布局控制:未给图片添加排列规则,无法实现指定数量水平、垂直排列的效果
  • 输入值未转数字类型:从input获取的value是字符串类型,直接做数值判断会有异常风险

完整修复代码

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
   <form id="grid">
      期望垂直重复次数:<input type="text" id="height">
      期望水平重复次数:<input type="text" id="length">
      <input type="button" value="提交" id="submit">
   </form>
</div>
<div id="choc-container"></div>

CSS

.choc-row {
  display: flex;
}
.choc-img {
  /* 可根据实际图片尺寸调整宽高 */
  width: 50px;
  height: 50px;
}

JavaScript

const button = document.getElementById("submit");
const container = document.getElementById("choc-container");
// 替换为你实际的图片存储路径
const IMG_PATH = "../img/chocci.png";

function imgRep() {
  // 将输入值转换为整数
  const horizontalCount = parseInt(document.getElementById("length").value);
  const verticalCount = parseInt(document.getElementById("height").value);
  
  // 输入合法性全量校验
  if (isNaN(horizontalCount) || isNaN(verticalCount) || horizontalCount < 1 || verticalCount < 1 || horizontalCount > 10 || verticalCount > 10) {
    alert("请输入1-10之间的合法数值!");
    return;
  }
  
  // 清空之前生成的所有图片
  container.innerHTML = "";
  
  // 外层循环控制垂直行数
  for (let rowIndex = 0; rowIndex < verticalCount; rowIndex++) {
    const rowEl = document.createElement("div");
    rowEl.className = "choc-row";
    // 内层循环控制单行水平展示的图片数量
    for (let colIndex = 0; colIndex < horizontalCount; colIndex++) {
      const img = document.createElement("img");
      img.src = IMG_PATH;
      img.className = "choc-img";
      rowEl.appendChild(img);
    }
    container.appendChild(rowEl);
  }
}
          
button.onclick = function() {
  imgRep();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:06:04