2016-06-22 76 views
1

我需要顯示在選項塊中的JavaScript腳本中聲明的變量。將會有一到兩個更多的選擇塊,它們取決於此塊中選擇的選項。如何在選項標記中顯示javascript變量

<select name="expiration_year" id="expiration_year" onchange="populate(this.id,'expiration_month','expiration_day')"> 

    <script> 
    //variable declaration in JavaScript 
    var year = new Date().getFullYear(); 
    </script> 

    //I want to display the variable stored in "year" where it is marked in the 
    //following code 
    //this <option value=year> is using the variable correctly, the second 
    //half of the line isnt using the variable (which should have a value 
    //equaling the current year) 
    //instead it simply says year 
    <select> 
    <option value=year>year</option> 
    <option value=year+1>year+1</option> 

    </select>   

Image of what current code produces when run

任何幫助都將不勝感激,我很非常新編碼的網頁和使用Java腳本。如果這個問題已經被詢問並回答,我很抱歉。

回答

0

你可以動態地添加你的選項。

例如

// This assumes that this is the only select element on the page. 
// Also, this would have to run in a script block 
// after the select element is added to the page. 
var select = document.querySelector('select'); 
select.options.add(new Option(year)); 
select.options.add(new Option(year + 1)); 

// etc. 
+0

感謝您的迴應!我的最終目標是,網頁上共有三個選擇。與依賴的順序是年==>月==>日。年月和日是選擇的名稱。我已更新問題以反映將會有多個選擇。再次感謝! – brandontod97

相關問題