MasterPage 遇到clientID 的解決方法
問題: 為網頁加上masterpage時,每個ASP控制項的id都會被附予新的id
如:id="TextBox1"就變成,id="ctl00_ContentPlaceHolder1_TextBox1"
alert(document.getElementById("TextBox1").value);==>會產生錯誤
解決: 用 MyGetElementById 取代 document.getElementById
<MasterPage.master.cs>
#region "javaScript 用 MyGetElementById 取代 document.getElementById"
/// <summary>RegisterMPGet
///問題: 為網頁加上masterpage時,每個ASP控制項的id都會被附予新的id
/// 如:id="TextBox1"就變成,id="ctl00_ContentPlaceHolder1_TextBox1"
/// alert(document.getElementById("TextBox1").value);==>會產生錯誤
///
///解決: 用 MyGetElementById 取代 document.getElementById
///</summary>
public static void RegisterMPGet(MasterPage mp)
{
List<string> lstCph = new List<string>();
lstCph.Add(mp.ClientID);
searchContentPlaceHolder(mp.Page.Form, lstCph);
StringBuilder sb = new StringBuilder();
sb.Append(@" <script type=""text/javascript""> " + "\r\n");
sb.Append(@" function MyGetElementById(objId) {" + "\r\n");
sb.Append(@" var inp = document.getElementById(objId);" + "\r\n");
foreach (string cphId in lstCph)
{
sb.AppendFormat(" if (!inp) inp = document.getElementById(\"{0}_\" + objId);\n", cphId);
}
sb.Append(" return inp;\n}\n </script>");
Literal js = new Literal();
js.Text = sb.ToString();
mp.Page.Header.Controls.AddAt(0, js);
}
public static void searchContentPlaceHolder(Control ctrl, List<string> lst)
{
if (ctrl is ContentPlaceHolder)
lst.Add(ctrl.ClientID);
else if (ctrl.HasControls())
foreach (Control c in ctrl.Controls)
searchContentPlaceHolder(c, lst);
}
#endregion
<Test1.ASPX>
<script language="javascript" type="text/javascript" >
function preCheck() {
var strSettle_Date_BGN;
strSettle_Date_BGN = MyGetElementById("txtSettle_Date_BGN").value;
if (strSettle_Date_BGN== "") { alert("請輸入 請款日(起日)!"); MyGetElementById("txtSettle_Date_BGN").focus() ; return (false); }
</script>