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