JavaScript循环结构开发:调用函数生成带感叹号的有序列表
修正代码实现有序列表循环输出需求
修正后的JavaScript代码
function displayHello() { const name = document.getElementById("helloNameInput").value.trim(); // 转换为数字,默认0防止非数字输入 let numOfTimes = parseInt(document.getElementById("numOfTimesInput").value) || 0; // 清空之前的列表内容 const outputList = document.getElementById("helloNameOutput"); outputList.innerHTML = ""; // 调用生成列表的函数 addOrderListItems(name, numOfTimes); } function addOrderListItems(name, numOfTimes) { const outputList = document.getElementById("helloNameOutput"); // 从1开始循环到指定次数 for (let i = 1; i <= numOfTimes; i++) { const listItem = document.createElement("li"); let text = `Hello ${name}`; // 偶数序号添加感叹号 if (i % 2 === 0) { text += "!"; } listItem.textContent = text; outputList.appendChild(listItem); } } function clearName() { document.getElementById("helloNameInput").value = ""; document.getElementById("numOfTimesInput").value = ""; document.getElementById("helloNameOutput").innerHTML = ""; }
优化后的HTML代码(可选,提升输入体验)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JavaScript: Looping Structures Assignment</title> <link href="/bootstrap.min.css" rel="stylesheet" /> </head> <body class="p-3"> <h1>JavaScript: Looping Structures Assignment</h1> <!--Name input--> <div class="mb-3"> <label for="helloNameInput" class="form-label">Name:</label> <input type="text" class="form-control" name="helloNameInput" id="helloNameInput" placeholder="Enter a name" /> </div> <!--Number of Times input--> <div class="mb-3"> <label for="numOfTimesInput" class="form-label">Number of Times:</label> <input type="number" <!-- 改为数字类型,避免非数字输入 --> class="form-control" name="numOfTimesInput" id="numOfTimesInput" placeholder="Enter number" min="1" <!-- 限制最小输入为1 --> /> </div> <!--Name output--> <ol id="helloNameOutput"></ol> <!--Display Hello! & Reset buttons--> <div> <button class="btn btn-primary" id="displayHelloButton" onclick="displayHello();"> Display Hello! </button> <button class="btn btn-danger" id="clearButton" onclick="clearName();">Clear</button> </div> <script src="/script.js"></script> </body> </html>
关键修改说明
- displayHello函数:
- 对输入的姓名做去空格处理,避免空内容异常
- 将次数输入转换为数字类型,防止字符串导致循环逻辑错误
- 调用
addOrderListItems时传入所需参数,生成新列表前清空原有内容
- addOrderListItems函数:
- 新增
name和numOfTimes参数接收外部传入值 - 使用
for循环从1开始遍历到指定次数,匹配有序列表的序号逻辑 - 通过创建
<li>元素追加到列表,避免innerHTML覆盖已有内容 - 判断当前序号是否为偶数,为偶数时在文本末尾添加
!
- 新增
- HTML优化:
- 将次数输入框改为
number类型并添加min="1"限制,减少非法输入
- 将次数输入框改为
输入姓名Braden、次数8时,会生成符合要求的输出:
- Hello Braden
- Hello Braden!
- Hello Braden
- Hello Braden!
- Hello Braden
- Hello Braden!
- Hello Braden
- Hello Braden!
内容的提问来源于stack exchange,提问作者nightowl898
相关产品推荐
相关产品推荐

