JavaScript与DropDownList 区别分析


Posted in Javascript onJanuary 01, 2010

比如<asp:LinkButton>控件就被渲染成了<a>锚点控件,这里要讲的DropDownList控件也一样,被渲染成了普通的select控件,在如下的asp.net页面中定义了一个web服务器控件DropDownList和一个普通的select控件(主要为了对比)。
代码

<asp:DropDownList ID = "ddlCities" runat = "server"> 
<asp:ListItem Value = "0">长沙</asp:ListItem> 
<asp:ListItem Value = "1">北京</asp:ListItem> 
<asp:ListItem Value = "2">天津</asp:ListItem> 
<asp:ListItem Value = "3">漠河</asp:ListItem> 
</asp:DropDownList> 
<select id = "ddlNames" runat ="server"> 
<option value = "0">James</option> 
<option value = "1">Green</option> 
<option value = "2">Lily</option> 
<option value = "3">Lucy</option> 
</select>

在浏览器中查看该页面,并点击查看源文件,不难看出,asp.net页面被渲染成了如下格式:
代码

<select name="ddlCities" id="ddlCitys"> 
<option value="0">长沙</option> 
<option value="1">北京</option> 
<option value="2">天津</option> 
<option value="3">漠河</option> 
</select> 
<select name="ddlNames" id="ddlNames"> 
<option value="0">James</option> 
<option value="1">Green</option> 
<option value="2">Lily</option> 
<option value="3">Lucy</option> 
</select>

好了,接下来介绍一下要用javascript操纵DropDownList控件,首先得了解select(或者DropDownList)的两个最基本的属性,一个是value属性,一个是text属性,还有一个selectedIndex属性,用来标识当前选中的项(数字),具体可参见上面的示例代码。
下面正式言归正传,主要介绍如下几点:
(1) 清空DropDownList控件中的值。


document.getElementById('ddlCities').options.length = 0;
(2) 判断DropDownList中是否有value为'Param1'的ListItem。

function isListItemExist(objDdl , objItemValue) 
{ 
var isExist = false; 
for(var i in objSelect.options) 
{ 


if(i.value == objItemValue) 


{ 



isExist = true; 



break; 


} 

} 

return isExist; 
}

JavaScript与DropDownList
服务器控件DropDownList和Javascript的之间的传递
<script language="javascript"> 
function hehe() 
{ 
document.all('txtSdept').value =document.all('ddlSdept').options[document.all('ddlSdept').selectedIndex].text; 
} 
</script> 
<asp:DropDownList id="ddlSdept" style="Z-INDEX: 101; LEFT: 240px; POSITION: absolute; TOP: 112px" onchange="hehe()" runat="server"> 
<asp:ListItem Value="1">计算机系</asp:ListItem> 
<asp:ListItem Value="2">机械系</asp:ListItem> 
<asp:ListItem Value="3">电子系</asp:ListItem> 
<asp:ListItem Value="4">英语系</asp:ListItem> 
<asp:ListItem Value="5">中文系</asp:ListItem> 
</asp:DropDownList> 
<asp:TextBox id="txtSdept" style="Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 112px" runat="server"></asp:TextBox>

参考文章:
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<title>无标题文档</title> 
<script language="javascript"> 
function moveSelected(select, down) 
{ 
if (select.selectedIndex != -1) 
{ 
if (down) 
{ 
if (select.selectedIndex != select.options.length - 1) 
var i = select.selectedIndex + 1; 
else 
return; 
} 
else 
{ 
if (select.selectedIndex != 0) 
var i = select.selectedIndex - 1; 
else 
return; 
} 
var swapOption = new Object(); 
swapOption.text = select.options[select.selectedIndex].text; 
swapOption.value = select.options[select.selectedIndex].value; 
swapOption.selected = select.options[select.selectedIndex].selected; 
swapOption.defaultSelected = select.options[select.selectedIndex].defaultSelected; 
for (var property in swapOption) 
select.options[select.selectedIndex][property] = select.options[property]; 
for (var property in swapOption) 
select.options[property] = swapOption[property]; 
} 
} 
<form id="formName" name="formName" > 
<select name="selectName" id="selectName" size="8"> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
<option>4</option> 
<option>5</option> 
<option>6</option> 
<option>7</option> 
</select> 
<input id="moveUp" onclick="moveSelected(this.form.selectName, false)" type="button" value="上移" /> 
<input id="moveDown" onclick="moveSelected(this.form.selectName, false)" type="button" value="下移" /> 
</form>

1、js脚本如何访问服务器控件的值
界面上有一个TextBox控件,ID为Name,js里可以采用如下脚本取Name的值
var myvalue=document.all('Name').value;
2、服务器控件如何取js中变量的值
目前未发现比较好的办法,我通常采用的方法是在界面上放一个隐藏的控件HtmlInputHidden,然后设置为以服务器控件运行,这样在js脚本中和ASP.NET代码里都可以访问到该控件的值
js中给服务器控件赋值:
var bt=document.all('Name').value;
bt.value='名称';
ASP.NET中使用Name.Value来访问。
3、如何遍历界面上所有TextBox元素
var inputList = document.body.getElementsByTagName("INPUT"); 
for(var i=0;i<inputList.length;i++) 
{ 
if(inputList.disabled==false && (inputList.type=='text' || inputList.type=='password')) 
{ 
inputList.value=""; 
} 
}

4、让dropdownlist选择到指定项
选择dropdownlist中值为“我得选择”得项
var handl=document.all('List1'); 
var my_value='我得选择'; 
for(var index=0;index<handle.options.length;index++) 
{ 
if(handle.options[index].text==my_value) 
{ 
handle.selectedIndex=index; 
} 
}

JS取消ListBox,Select,DropDownList选项的选中
<asp:ListBox ID="ListBox1" runat="server"> 
<asp:ListItem Text="1" Value="1"></asp:ListItem> 
<asp:ListItem Text="2" Value="2"></asp:ListItem> 
<asp:ListItem Text="3" Value="3"></asp:ListItem> 
<asp:ListItem Text="4" Value="4"></asp:ListItem> 
<asp:ListItem Text="5" Value="5"></asp:ListItem> 
</asp:ListBox> 
<script language="javascript" type="text/javascript"> 
$(document).ready(function(){ 
$("#cel").click(function(){ 
$("#<%=ListBox1.ClientID%>").get(0).selectedIndex=-1; 
}); 
}); 
</script> 
<div id="cel" style="cursor:pointer;">取消绑定</div>

dropdownlist 选中值
c#:
ddlProvince.SelectedIndex = ddlProvince.Items.IndexOf(ddlProvince.Items.FindByText( "浙江")); 
javascript: 
var requiredSdept=$("select[@id='ddlSdept'] option[@selected]").val(); 
var requiredSdept = $("#ddlSdept option[@selected]").text(); 
var select1 = document.all.<%= ddlSdept.ClientID %>; 
var select1value = select1.options[select1.selectedIndex].value; 
var select1Text = select1.options[select1.selectedIndex].innerText; 
其中select1Text 为选中的值。如果在模态窗口中使用,可以用如下代码: 
window.returnValue=select1Text;//这是返回给父窗体的值 
window.close();

javascript中设定dropdownlist哪一项为当前选中项
方法1:
i = 2
document.all.dropdownlistID.options[i].selected=true
方法2:
obj.selectedIndex = 2;
方法3:
obj.value="你要设的数值。"//Dropdownlist就会自动把那个值设为当前。
javascript清除dropdownlist的项
//清除原有项 
function clearitem(){ 
var drp1 = document.getElementById("drp1"); 
while(drp1.options.length>0) 
{ 
drp1.options.remove(0); 
} 
}

动态更改方法(根据城市代码取得该市商业区并添加到DropDownList中)
function getsyq() 
{ 
var city = document.getElementById("DropDownList_Cities").value;//取得城市代码 
var htp = new ActiveXObject("Msxml2.XMLHTTP"); 
var drp1 = document.getElementById("drp1");  
var url = "?stat=1&city="+city
 
htp.open("post",url,true) 
htp.onreadystatechange=function() 
{ 
if(htp.readyState==4) 
{ 

 clearitem(); //清除原有下拉项 
var str = htp.responseText; 
var opt = str.split(','); 
var s = opt.length 
for(var j = 0;j<s;j++) 
{ 
var newOption = document.createElement("OPTION"); 
//定义一个新的项 
var ff = opt[j].split('|'); 

 newOption.text = ff[1]; 

 newOption.value = ff[1]; 

 drp1.options.add(newOption); 
  } 
} 
} 
htp.send() 
}

JavaScript实现DropDownList(Select)三级联动无刷新
<script language=javascript> 
function CountryChange(){ 
countryid=document.getElementById("ddlContry").value; 
if(countryid==null||countryid==""){ 
alert("请选择所属国家"); 
CountryDel("ddlProvince");//清空DropDownList 
CountryDel("ddlCity");//清空DropDownList 
return false; 
} 
var countrystring=""; 
var posturl=location.protocol+"//"+location.hostname+"//soleweb//AjaxEnjine//AreaShow.aspx?AreaId="+countryid; 
countrystring=openUrl(posturl); 
if(countrystring=="-2"){//查询失败 
alert("数据查询失败"); 
return false; 
} 
//分割并写入DropDownList 
CountryDel("ddlProvince");//清空DropDownList 
CountryDel("ddlCity");//清空DropDownList 
if(countrystring==""){ 
return false; 
} 
var stringarray=countrystring.split("|"); 
for(var i=0;i<stringarray.length;i++){//重写DropDownList 
//拆分内部数组 
var optionarray=stringarray[i].split(","); 
var newoption=document.createElement("option"); 
newoption.text=optionarray[0]; 
newoption.value=optionarray[1]; 
document.getElementById("ddlProvince").options.add(newoption); 
} 
} 
function CountryDel(AreaName){//清空DropDownList 
var countnum=document.getElementById(AreaName).options.length; 
for(var i=1;i<countnum;i++){//清空DropDownList 
document.getElementById(AreaName).remove(countnum-i); 
} 
} 
function ProvinceChange(){ 
countryid=document.getElementById("ddlProvince").value; 
if(countryid==null||countryid==""){ 
alert("请选择所属省"); 
CountryDel("ddlCity");//清空DropDownList 
return false; 
} 
var countrystring=""; 
var posturl=location.protocol+"//"+location.hostname+"//soleweb//AjaxEnjine//AreaShow.aspx?AreaId="+countryid; 
countrystring=openUrl(posturl); 
if(countrystring=="-2"){//查询失败 
alert("数据查询失败"); 
return false; 
} 
//分割并写入DropDownList 
CountryDel("ddlCity");//清空DropDownList 
if(countrystring==""){ 
return false; 
} 
var stringarray=countrystring.split("|"); 
for(var i=0;i<stringarray.length;i++){//重写DropDownList 
//拆分内部数组 
var optionarray=stringarray[i].split(","); 
var newoption=document.createElement("option"); 
newoption.text=optionarray[0]; 
newoption.value=optionarray[1]; 
document.getElementById("ddlCity").options.add(newoption);
 
} 
} 
function openUrl(url) 
{ 
var objxml=new ActiveXObject("Microsoft.XMLHttp") 
objxml.open("GET",url,false); 
objxml.send(); 
retInfo=objxml.responseText; 
if (objxml.status=="200") 
{ 
return retInfo; 
} 
else 
  { 
return "-2"; 
} 
} 
</script>

Html代码
<asp:DropDownList ID="ddlContry" runat="server" onchange="CountryChange()" OnSelectedIndexChanged="ddlContry_SelectedIndexChanged"> 
<asp:ListItem Value=" ">请选择所属国家</asp:ListItem> 
</asp:DropDownList> 
<asp:DropDownList ID="ddlProvince" runat="server" onchange="ProvinceChange()" OnSelectedIndexChanged="ddlProvince_SelectedIndexChanged"> 
<asp:ListItem Value=" ">请选择所属省</asp:ListItem> 
</asp:DropDownList> 
<asp:DropDownList ID="ddlCity" runat="server"> 
<asp:ListItem Value=" ">请选择所属市</asp:ListItem> 
</asp:DropDownList>

Aspx.cs代码
protected void Page_Load(object sender, EventArgs e) 
{ 
SoLe.Common.StringFormat sft = new SoLe.Common.StringFormat(); 
string AreaId = sft.Html_Fn(Request.QueryString["AreaId"].ToString()); 
StringBuilder AreaString = new StringBuilder(); 
AreaString.Append(""); 
if (!Page.IsPostBack) 
{ 
//Response.Write(AreaIdValid(AreaId.ToString())); 
SoLe.BLL.AreaTable bll = new SoLe.BLL.AreaTable(); 
DataSet ds = new DataSet(); 
ds = bll.GetList(" PaterId=" + AreaId.ToString()+" "); 
if (!object.Equals(ds, null) && ds.Tables[0].Rows.Count > 0) { 
for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { 
if (string.IsNullOrEmpty(AreaString.ToString())) 
{ 
AreaString.Append(ds.Tables[0].Rows[i]["Title"].ToString() + "," + ds.Tables[0].Rows[i]["Id"].ToString()); 
} 
else { 
AreaString.Append("|" + ds.Tables[0].Rows[i]["Title"].ToString() + "," + ds.Tables[0].Rows[i]["Id"].ToString()); 
} 
} 
} 
} 
Response.Write(AreaString.ToString()); 
}

JavaScript分割字符串装载到DropDownList
假设变量str存放着几组对应的数据,DropDownList名为ddlType,把字符分隔后的数据装载到ddlType,具体代码如下:
程序代码
<script language="javascript"> 
function LoadType() { 
var str = "1|网页|2|图片|3|企业|4|资讯|"; 
var temp = str.split("|"); 
var count = (temp.length - 1) / 2; 
for (var i = 0; i <= count; i++) { 
document.all("ddlType").options.add(new Option(temp[i], temp[i + 1])); 
} 
return; 
} 
<script>
Javascript 相关文章推荐
使用jQuery fancybox插件打造一个实用的数据传输模态弹出窗体
Jan 15 Javascript
JavaScript获取多个数组的交集简单实例
Nov 11 Javascript
node.js中的http.response.writeHead方法使用说明
Dec 14 Javascript
推荐4个原生javascript常用的函数
Jan 12 Javascript
JavaScript中实现无缝滚动、分享到侧边栏实例代码
Apr 06 Javascript
关于Node.js中Buffer的一些你可能不知道的用法
Mar 28 Javascript
基于Bootstrap table组件实现多层表头的实例代码
Sep 07 Javascript
基于Vue2.0+ElementUI实现表格翻页功能
Oct 23 Javascript
解决layui-table单元格设置为百分比在ie8下不能自适应的问题
Sep 28 Javascript
Vue 解决多级动态面包屑导航的问题
Nov 04 Javascript
vue.js的简单自动求和计算实例
Nov 08 Javascript
原生js+css实现tab切换功能
Sep 17 Javascript
HTML node相关的一些资料整理
Jan 01 #Javascript
JQery 渐变图片导航效果代码 漂亮
Jan 01 #Javascript
jquery 简短右键菜单 多浏览器兼容
Jan 01 #Javascript
使用JQUERY Tabs插件宿主IFRAMES
Jan 01 #Javascript
用jquery实现学校的校历(asp.net+jquery ui 1.72)
Jan 01 #Javascript
url 特殊字符 传递参数解决方法
Jan 01 #Javascript
JavaScript 数组循环引起的思考
Jan 01 #Javascript
You might like
PHP中让curl支持sock5的代码实例
2015/01/21 PHP
laravel5使用freetds连接sql server的方法
2018/12/07 PHP
js实时监听文本框状态的方法
2011/04/26 Javascript
javascript获取所有同类checkbox选项(实例代码)
2013/11/07 Javascript
使用jquery局部刷新(jquery.load)从数据库取出数据
2014/01/22 Javascript
使用js实现一个可编辑的select下拉列表
2014/02/20 Javascript
JavaScript实现找出字符串中第一个不重复的字符
2014/09/03 Javascript
JavaScript使用concat连接数组的方法
2015/04/06 Javascript
JavaScript实现鼠标滑过图片变换效果的方法
2015/04/16 Javascript
Javascript中的作用域和上下文深入理解
2015/07/03 Javascript
JavaScript+canvas实现七色板效果实例
2016/02/18 Javascript
js正则表达式验证表单【完整版】
2017/03/06 Javascript
微信小程序 图片宽度自适应的实现
2017/04/06 Javascript
jquery Form轻松实现文件上传
2017/05/24 jQuery
详解webpack+angular2开发环境搭建
2017/06/28 Javascript
Vue使用vue-cli创建项目
2017/09/01 Javascript
angular2系列之路由转场动画的示例代码
2017/11/09 Javascript
Vue插槽原理与用法详解
2019/03/05 Javascript
M2实现Nodejs项目自动部署的方法步骤
2019/05/05 NodeJs
Element DateTimePicker日期时间选择器的使用示例
2020/07/27 Javascript
[49:41]NB vs NAVI Supermajor小组赛A组 BO3 第一场 6.2
2018/06/03 DOTA
理解Python中的With语句
2015/02/02 Python
Python的Flask框架中集成CKeditor富文本编辑器的教程
2016/06/13 Python
python读取TXT每行,并存到LIST中的方法
2018/10/26 Python
python读取几个G的csv文件方法
2019/01/07 Python
python django中8000端口被占用的解决
2019/12/17 Python
如何使用Python抓取网页tag操作
2020/02/14 Python
Python3 pywin32模块安装的详细步骤
2020/05/26 Python
video.js支持m3u8格式直播的实现示例
2020/05/20 HTML / CSS
Jacadi Paris英国官网:法国童装品牌
2019/08/09 全球购物
Steiff台湾官网:德国金耳釦泰迪熊
2019/12/26 全球购物
营销总监岗位职责范本
2014/02/26 职场文书
高校自主招生自荐信2015
2015/03/04 职场文书
nginx如何将http访问的网站改成https访问
2021/03/31 Servers
JavaScript 定时器详情
2021/11/11 Javascript
Java实现二分搜索树的示例代码
2022/03/17 Java/Android