javascript - 如何通过 JavaScript 在 HTML 中打印结果
问题描述
我是 JavaScript 的初学者。我无法在 HTML 中打印此代码..
我希望当用户在第一个输入中添加值和第二个输入使选择框多年..
var firstInput = document.getElementById("firstInput").value,
secondInput = document.getElementById("secondInput").value,
myDiv = '',
myResult = document.getElementById("result");
function theYears() {
"use strict";
var years;
for (years = firstInput; years <= secondInput; years += 1) {
myDiv += '<select><option>' + years + '</option></select>';
}
}
myResult.innerHTML = myDiv;
<input type="text" id="firstInput">
<input type="text" id="secondInput">
<input type="button" id="excute" value="Enter" onclick="theYears();">
<div id="result"></div>
解决方案
几个问题:
- 您需要获取函数中输入的值。当页面首次加载时,在用户填写之前,您将获得这些值。
- 您需要调用
parseInt()
将值从字符串转换为数字。否则,years += 1
将执行字符串连接,而不是添加。 - 您需要
innerHTML
在函数中分配给。您是在页面加载时执行此操作,而不是在用户单击按钮时执行此操作。 - 您不应该
<select>
每次都重复循环。在循环之前创建<select>
一次,然后<option>
在循环中添加。
function theYears() {
"use strict";
var firstInput = parseInt(document.getElementById("firstInput").value),
secondInput = parseInt(secondInput = document.getElementById("secondInput").value),
myDiv = '',
myResult = document.getElementById("result");
var years;
myDiv = "<select>";
for (years = firstInput; years <= secondInput; years += 1) {
myDiv += '<option>' + years + '</option>';
}
myDiv += "</select>";
myResult.innerHTML = myDiv;
}
<input type="text" id="firstInput">
<input type="text" id="secondInput">
<input type="button" id="excute" value="Enter" onclick="theYears();">
<div id="result"></div>
推荐阅读
- outlook-addin - UI.displayDialogAsync() 在 Outlook 2013 中不起作用
- batch-file - 尝试在 Windows 查看器中批量打开所有 .png 文件
- angular - Cache-Control 在 Angular cli 中不起作用
- ios - 允许后,Google 登录重定向到 google.com 而不是应用程序
- .net - EF Core + npgsql DateTime 使用 windows 10 本地化进行格式化
- facebook - 在最新政策更改后,我的应用是否允许使用 API 作为 Facebook 页面发布而无需人工交互?(自 2018 年 4 月 24 日起)
- angular - 从 Angular 中的 Firebase 存储获取下载 URL
- node.js - 地址栏 url 在刷新页面时被附加到请求的静态资源中,如何处理?
- python - 使用 groupby 和 loc 建立一个新的数据框
- javascript - 无法读取未定义的属性 parentNode