簡體   English   中英

如何通過JavaScript在HTML中打印結果

[英]How I can print result in HTML by JavaScript

我是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> 

幾個問題:

  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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM