asp.net中使用JS
方法1,
使用Response.Write,这种方法会把JS代码写在页面的最顶部(<html>的前面):
System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('JS代码');</script>");
方法2,
使用RegisterStartupScript,这种方法会把JS代码嵌入在页面的底部、表单的最后 (</form>前面),适用于要在页面控件加载完成后运行的JS代码 :
System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(),"clientScript"))
page.ClientScript.RegisterStartupScript(page.GetType(), "clientScript", "<script language=javascript>alert('JS代码');</script>");
方法3,
使用RegisterClientScriptBlock,这种方法会把JS代码嵌入在页面的顶部、表单的最前 (<form>后面),适用于要在控件加载前执行的JS代码,类似于上面的Response.Write方式 :
System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
if (!page.ClientScript.IsClientScriptBlockRegistered(page.GetType(),"clientScript"))
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "clientScript", "<script language=javascript>alert('JS代码');</script>");
列子:
///<summary>
///控件点击消息确认提示框
///</summary>
///<param name="page">当前页面环境,一般为this</param>
///<param name="msg">要显示的信息</param>
///<param name="trueDoSomething">如果点确定后要做的事(JavaScript脚本)</param>
///<param name="falseDoSomething">如果点取消后要做的事(JavaScript脚本)</param>
public static void ShowConfirm(System.Web.UI.Page page, string msg, string trueDoSomething, string falseDoSomething)
{
StringBuilder Builder = new StringBuilder();
Builder.Append("<SCRIPT language='JavaScript' defer>");
Builder.Append("if(confirm ('" + msg + "')){");
Builder.Append("" + trueDoSomething + "}");
Builder.Append("else{");
Builder.Append("" + falseDoSomething + "}");
Builder.Append("</SCRIPT>");
page.ClientScript.RegisterStartupScript(page.GetType(), "message", Builder.ToString());
}
1.动态创建select
function createSelect(){
var mySelect = document.createElement(select);
mySelect.id = mySelect;
document.body.appendChild(mySelect);
}
2.添加选项option
function addOption(){
根据id查找对象,
var obj=document.getElementById('mySelect');
添加一个选项
obj.add(new Option(文本,值));
}
3.删除所有选项option
function removeAll(){
var obj=document.getElementById('mySelect');
obj.options.length=0;
}
4.删除一个选项option
function removeOne(){
var obj=document.getElementById('mySelect');
index,要删除选项的序号,这里取当前选中选项的序号
var index=obj.selectedIndex;
obj.options.remove(index);
}
5.获得选项option的值
var obj=document.getElementById('mySelect');
var index=obj.selectedIndex; 序号,取当前选中选项的序号
var val = obj.options[index].value;
6.获得选项option的文本
var obj=document.getElementById('mySelect');
var index=obj.selectedIndex; 序号,取当前选中选项的序号
var val = obj.options[index].text;
7.修改选项option
var obj=document.getElementById('mySelect');
var index=obj.selectedIndex; 序号,取当前选中选项的序号
var val = obj.options[index]=new Option(新文本,新值);
8.删除select
function removeSelect(){
var mySelect = document.getElementById(mySelect);
mySelect.parentNode.removeChild(mySelect);
}
转自http://www.cnblogs.com/rayking/archive/2008/09/03/1282473.html