首页 > 解决方案 > 如何通过 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>

标签: javascript

解决方案


几个问题:

  1. 您需要获取函数中输入的值。当页面首次加载时,在用户填写之前,您将获得这些值。
  2. 您需要调用parseInt()将值从字符串转换为数字。否则,years += 1将执行字符串连接,而不是添加。
  3. 您需要innerHTML在函数中分配给。您是在页面加载时执行此操作,而不是在用户单击按钮时执行此操作。
  4. 您不应该<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>


推荐阅读