运行后 总是得出 undefind
我也觉得这样写有什么问题。请高人指点
如果一定要在运行是给它添加事件
应如何改?
以下是代码段:
aspx:
------------------------------------------------------------
<html>
<head>
<script language="javascript" type="text/javascript" src="Script/Default.js"></script>
</head>
<body>
<form id="frim1" runat="sever" action="">
<asp:DropDownList ID="ddl" runat="sever"></DropDownList>
</form>
<body>
-----------------------------------------------
cs:
--------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddl.Attributes.Add("onChange", "javascript:TextBoxEnable("ddl")");
}
}
-------------------------------------
js
-----------------------------------------
function TextBoxEnable(ddlName)
{
ddl=document.getElementById(ddlName);
index =ddl.seletedIndex;
alert(index);
}
写了个完整的代码给你贴在下面
这是html代码<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value="1">我是1个一</asp:ListItem>
<asp:ListItem Value="2">我是2个二</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
<script type="text/javascript">
function sel(oid) {
oid = document.getElementById(oid);
var index = oid.options[oid.selectedIndex].value;
alert(index);
}
</script>
这是c#代码
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) this.DropDownList1.Attributes.Add("OnChange", "return sel('DropDownList1')");
}
}
ddl=document.getElementById(ddlName);
index =ddl.value;
;
楼上是的正解,不过只能得到选中的值,不能得到序号。
如果你想理解dropdownlist你可以看一下HTML 标记中select标签有哪些属性。
查看生成的html源码,看看ddl生成的id是什么。在asp.net 1.1里面是ddl,但在2.0以后的生成的ID往往会有些前缀的
楼主,改这三个位置的代码。
from:ddl.Attributes.Add("onChange", "TextBoxEnable("ddl")");
to:ddl.Attributes.Add("onChange", "TextBoxEnable(this)");
from:function TextBoxEnable(ddlName)
to:function TextBoxEnable(el)
from:ddl=document.getElementById(ddlName);
index =ddl.seletedIndex;
to:index=el.selectedIndex;