如何用JS选中下拉框选项

JavaScript02

如何用JS选中下拉框选项,第1张

1、打开vscode,创建一个H5规范的页面,用于演示js如何给下拉框设置默认值。

2、在页面中添加一个下拉框,并在html中通过selected属性,默认选择下拉框的第2个值。

3、在浏览器中打开页面,就可以看到这个下拉框默认选中的第二个下拉值。

4、在页面顶部引入jquery,由于本文将jquery和页面放在同一级目录,所以,直接使用了jquery文件名引用。如果不在同一级目录,引入的路径需要有层级。

5、在页面底部,添加jquery代码,使用.val()方法,在页面文档加载后,就马上修改下拉框的默认选中值为第三个值。此时是不管html的标签中selected属性原来是标记在哪一个选项的,都会改成新的值。

6、在浏览器中打开页面,这个时候就会看到,下拉框的默认值已经变成了第三个选项。

7、如果想要通过下拉框的显示值来设置默认选中项,就需要使用类似下面的语法:

$("#sltDef").find("option:contains('第4个选项')").attr("selected", true)

首先结构如下:

<style>.nav>li {width:120pxheight:40pxdisplay:inline-blockpadding:5px 15pxbackground:#dddtext-align:center}.nav li ul {display:none}.subnav li {padding:5px}.nav li:hover .subnav {display:blockbackground: #e8e8e8}

</style>

<ul class="nav">

<li><a href="">一级菜单1</a>

<ul class="subnav">

<li><a href="">2级菜单</a></li>

<li><a href="">2级菜单</a></li>

</ul>

</li>

<li><a href="">一级菜单2</a>

<li><a href="">一级菜单3</a>

</ul>

<style type="text/css">

#mainMenu{

background-color: #FFF/* Background color of main menu */

font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif/* Fonts of main menu items */

font-size:1.2em/* Font size of main menu items */

border-bottom:1px solid #000000/* Bottom border of main menu */

height:30px/* Height of main menu */

position:relative/* Don't change this position attribute */

visibility: hidden

}

#mainMenu a{

padding-left:20px/* Spaces at the left of main menu items */

padding-right:20px/* Spaces at the right of main menu items */

font-weight: bold

/* Don't change these two options */

position:absolute

bottom:-1px

}

#submenu{

font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif/* Font of sub menu items */

background-color:#E2EBED/* Background color of sub menu items */

visibility: hidden

width:778px/* Don't change this option */

}

html>body #clearmenu{ /* non IE browsers menu bottom spacing */

margin-bottom: 2px

}

#submenu div{

white-space:nowrap/* Don't change this option */

}

/*

Style attributes of active menu item

*/

#mainMenu .activeMenuItem{

/* Border options */

border-left:1px solid #000000

border-top:1px solid #000000

border-right:1px solid #000000

background-color: #E2EBED/* Background color */

cursor:pointer/* Cursor like a hand when the user moves the mouse over the menu item */

}

/*

Style attributes of inactive menu items

*/

#mainMenu .inactiveMenuItem{

color: #000/* Text color */

cursor:pointer/* Cursor like a hand when the user moves the mouse over the menu item */

}

#submenu a{

text-decoration:none/* No underline on sub menu items - use text-decoration:underlineif you want the links to be underlined */

padding-left:5px/* Space at the left of each sub menu item */

padding-right:5px/* Space at the right of each sub menu item */

color: #000/* Text color */

}

#submenu a:hover{

color: #FF0000/* Red color when the user moves the mouse over sub menu items */

}

</style>

<script type="text/javascript">

//more javascript from http://www.smallrain.net

var topMenuSpacer = 15// Horizontal space(pixels) between the main menu items

var activateSubOnClick = false// if true->Show sub menu items on click, if false, show submenu items onmouseover

var leftAlignSubItems = false // left align sub items t

var activeMenuItem = false// Don't change this option. It should initially be false

var activeTabIndex = 0// Index of initial active tab (0 = first tab) - If the value below is set to true, it will override this one.

var rememberActiveTabByCookie = true// Set it to true if you want to be able to save active tab as cookie

/*

These cookie functions are downloaded from

http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm

*/

function Get_Cookie(name) {

var start = document.cookie.indexOf(name+"=")

var len = start+name.length+1

if ((!start) &&(name != document.cookie.substring(0,name.length))) return null

if (start == -1) return null

var end = document.cookie.indexOf("",len)

if (end == -1) end = document.cookie.length

return unescape(document.cookie.substring(len,end))

}

// This function has been slightly modified

function Set_Cookie(name,value,expires,path,domain,secure) {

expires = expires * 60*60*24*1000

var today = new Date()

var expires_date = new Date( today.getTime() + (expires) )

var cookieString = name + "=" +escape(value) +

( (expires) ? "expires=" + expires_date.toGMTString() : "") +

( (path) ? "path=" + path : "") +

( (domain) ? "domain=" + domain : "") +

( (secure) ? "secure" : "")

document.cookie = cookieString

}

function showHide()

{

if(activeMenuItem){

activeMenuItem.className = 'inactiveMenuItem'

var theId = activeMenuItem.id.replace(/[^\d]/g,'')

document.getElementById('submenu_'+theId).style.display='none'

}

activeMenuItem = this

this.className = 'activeMenuItem'

var theId = this.id.replace(/[^\d]/g,'')

document.getElementById('submenu_'+theId).style.display='block'

if(rememberActiveTabByCookie){

Set_Cookie('dhtmlgoodies_tab_menu_tabIndex','index: ' + (theId-1),100)

}

}

function initMenu()

{

var mainMenuObj = document.getElementById('mainMenu')

var subMenuObj = document.getElementById('submenu')//DD added line

mainMenuObj.style.visibility=subMenuObj.style.visibility="visible" //DD added line

var menuItems = mainMenuObj.getElementsByTagName('A')

if(document.all){

mainMenuObj.style.visibility = 'hidden'

document.getElementById('submenu').style.visibility='hidden'

}

if(rememberActiveTabByCookie){

var cookieValue = Get_Cookie('dhtmlgoodies_tab_menu_tabIndex') + ''

cookieValue = cookieValue.replace(/[^\d]/g,'')

if(cookieValue.length>0 &&cookieValue<menuItems.length){

activeTabIndex = cookieValue/1

}

}

var currentLeftPos = 15

for(var no=0no<menuItems.lengthno++){

if(activateSubOnClick)menuItems[no].onclick = showHideelse menuItems[no].onmouseover = showHide

menuItems[no].id = 'mainMenuItem' + (no+1)

menuItems[no].style.left = currentLeftPos + 'px'

currentLeftPos = currentLeftPos + menuItems[no].offsetWidth + topMenuSpacer

if(no==activeTabIndex){

menuItems[no].className='activeMenuItem'

activeMenuItem = menuItems[no]

}else menuItems[no].className='inactiveMenuItem'

if(!document.all)menuItems[no].style.bottom = '-1px'

}

var mainMenuLinks = mainMenuObj.getElementsByTagName('A')

var subCounter = 1

var parentWidth = mainMenuObj.offsetWidth

while(document.getElementById('submenu_' + subCounter)){

var subItem = document.getElementById('submenu_' + subCounter)

if(leftAlignSubItems){

// No action

}else{

var leftPos = mainMenuLinks[subCounter-1].offsetLeft

document.getElementById('submenu_'+subCounter).style.paddingLeft = leftPos + 'px'

subItem.style.position ='absolute'

if(subItem.offsetWidth >parentWidth){

leftPos = leftPos - Math.max(0,subItem.offsetWidth-parentWidth)

}

subItem.style.paddingLeft = leftPos + 'px'

subItem.style.position ='static'

}

if(subCounter==(activeTabIndex+1)){

subItem.style.display='block'

}else{

subItem.style.display='none'

}

subCounter++

}

if(document.all){

mainMenuObj.style.visibility = 'visible'

document.getElementById('submenu').style.visibility='visible'

}

document.getElementById('submenu').style.display='block'

}

window.onload = initMenu

</script>

<div id="mainMenu">

<a>网页特效</a>

<a>插件下载</a>

<a>网络学院</a>

<a>网站联盟</a>

</div>

<div id="submenu">

<!-- The first sub menu -->

<div id="submenu_1">

<a href="http://www.smallrain.net/javascript.asp?type=图形图像">图形图像</a>

<a href="http://www.smallrain.net/javascript.asp?type=鼠标事件">鼠标事件</a>

<a href="http://www.smallrain.net/javascript.asp?type=时间日期">时间日期</a>

<a href="http://www.smallrain.net/javascript.asp?type=导航菜单">导航菜单</a>

<a href="http://www.smallrain.net/javascript.asp?type=文字效果">文字效果</a>

<a href="http://www.smallrain.net/javascript.asp?type=窗体变化">窗体变化</a>

</div>

<!-- Second sub menu -->

<div id="submenu_2">

<a href="http://www.smallrain.net/plug.asp?type=DreamWeaver插件">DreamWeaver插件</a>

<a href="http://www.smallrain.net/plug.asp?type=FireWork插件"FireWork插件</a>

<a href="http://www.smallrain.net/plug.asp?type=PhotoShop插件">PhotoShop插件</a>

<a href="http://www.smallrain.net/plug.asp?type=FLASH组件">FLASH组件</a>

</div>

<!-- Third sub menu -->

<div id="submenu_3">

<a href="http://www.smallrain.net/study.asp?type=网页制作">网页制作</a>

<a href="http://www.smallrain.net/study.asp?type=网络编程">网络编程</a>

<a href="http://www.smallrain.net/study.asp?type=图形图像">图形图像</a>

<a href="http://www.smallrain.net/study.asp?type=多媒体制作">多媒体制作</a>

<a href="http://www.smallrain.net/study.asp?type=网站建设">网站建设</a>

<a href="http://www.smallrain.net/study.asp?type=操作系统">操作系统</a>

</div>

<!-- Fourth sub menu -->

<div id="submenu_4">

<a href="http://www.smallrain.net/webmeng_show.asp?type=1">网页设计</a>

<a href="http://www.smallrain.net/webmeng_show.asp?type=2">艺术创作</a>

<a href="http://www.smallrain.net/webmeng_show.asp?type=3">电脑网络</a>

<a href="http://www.smallrain.net/webmeng_show.asp?type=4">生活休闲</a>

<a href="http://www.smallrain.net/webmeng_show.asp?type=5">个性展示</a>

<a href="http://www.smallrain.net/webmeng_show.asp?type=6">其它类型</a>

</div>

</div>

<br id="clearmenu" />