[英]Function that creates a drop down menu
因此,我首先要說的是,這是在學校里,不允許使用JQuery之類的東西。
我想要做的是編寫一個函數,該函數在我將其稱為具有特定長度的下拉菜單時創建,用於日期下拉菜單。
function date(start, end) {
var dateV ="";
for(i=start;i<=end;i++)
dateV += "<option value='"+i+"'>"+i+"</option>";
document.write(dateV);
}
Vars的起點和終點用於循環,例如,我使用1900作為起點,使用2014作為終點的年份。
此函數寫在外部文件中 (我們應該怎么做),但不起作用 。 但它工作 ,如果我寫在HTML頭這一功能
我試圖這樣稱呼它:
Day:
<select name="tag">
<script type="text/javascript" src="myjsfile.js">
date(1,31);
</script>
</select>
所以知道我現在想為什么它不能在外部文件中但在標頭中工作。 很多人已經告訴我, document.write()
可能是問題所在。 如果這是問題,我還可以使用其他什么功能?
編輯:
我怎么稱呼它:
<select name="tag" id="dd1">
<script type="text/javascript">
date(1,31,dd1);
</script>
</select>
多數民眾贊成在外部文件中的功能:
function date(start,end,div) {
var select1 = document.getElementById(div);
for(i=start;i<=end;i++){
var option = document.createElement("option");
option.text = i;
option.value= i;
select1.add(option);
}
}
第三個新參數是使其保持靜態,因為我需要幾天,幾個月和幾年的下拉菜單,然后每次都需要一個新的id(或?)
Day:
<select name="tag" id="ddl">
</select>
<script>
date(1,23);
function date(start,end)
{
var select1 = document.getElementById("ddl");
for(i=start;i<=end;i++){
var option = document.createElement("option");
option.text = i;
option.value= i;
select1.add(option);
}
}
</script>
Now its perfect JScript
Yes it does not use " $ " sign ,It is pure Javascript.There is no need of JQuery now.
Explanation =>
1)First i created variable "select1" which stores HTML element "ddl" (got it be its id).
2)Then we have start and end value. So till the value ends , Create HTML element "option" And store in it i)Value to be in <option> tag and ii)Text in it.
3) Then add that variable as child in the variable "select1".
//NEW CODE According to you
<html>
<head>
</head>
<body>
Day:
<select name="tag" id="ddl">
</select>
<script src="stk.js" type="text/javascript">
</script>
<script>
date(1,23);
</script>
</body>
</html>
//stk.js
function date(start,end)
{
var select1 = document.getElementById("ddl");
for(i=start;i<=end;i++){
var option = document.createElement("option");
option.text = i;
option.value = i;
select1.add(option);
}
}
您可以通過這種方式進行管理,嘗試以下代碼
在HTML代碼中添加ID
<select name="tag" id="dd"></select>
JavaScript的
<script>
function date(start, end) {
var dateV ="";
for(i=start;i<=end;i++)
dateV += "<option value='"+i+"'>"+i+"</option>";
document.getElementById('dd').innerHTML = dateV;
}
date(1, 10);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.