我正在開發一個元搜索引擎網站,Soogle和我用JS來填充選擇菜單..通過JS添加選擇菜單默認值?
現在,頁面加載沒有引擎的默認加載後,用戶需要選擇它他自己或[TAB]。
在頁面加載後,是否有可能通過JS從菜單中預選一個值?
這是代碼:
的Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>
嗯,它似乎沒有按預期工作,也許我複製/粘貼時發生錯誤,你可以發佈整個代碼來使用? – dzhi 2010-06-08 11:09:22
其實你的選擇=「網絡」正在工作。如果你想改變爲第一個以外的任何東西,你可以選擇sel.options [2] .selected = true;改爲第三個。這對我有用。 – mohang 2010-06-08 11:56:08
真的很奇怪,似乎我無法獲得選擇=「網絡」的工作.. – dzhi 2010-06-08 12:07:19