javascript 从内容页面访问母版页中的控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22359203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing controls in Master page from content page
提问by user3411907
I am trying to access control in Master page from Content page(Asp.net) using javascript like this
我正在尝试使用这样的 javascript 从内容页面(Asp.net)访问母版页中的控制
alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').value);
control in Master page is as follow,
母版页中的控制如下,
<asp:Label ID="lbl" runat="server" Text="one"></asp:Label>
But unfortunately it is not working. I am getting undefined value
但不幸的是它不起作用。我得到未定义的值
采纳答案by juan.facorro
I noticed that you are actually accessing the .value
field of the element that the <asp:Label />
control generates, which is a <span></span>
. This type of element won't return anything for the .value
attribute. If you are actually trying to access its text then use:
我注意到您实际上正在访问控件生成.value
的元素的字段<asp:Label />
,即<span></span>
. 这种类型的元素不会为该.value
属性返回任何内容。如果您实际上是在尝试访问其文本,请使用:
alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').innerText);
or
或者
alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').innerHTML);
回答by Ricardo Peres
The problem is that a master page is a naming container, hence the client id of the control receives a prefix which is the id of the naming container. Using JavaScript, it is easily solvable:
问题是母版页是一个命名容器,因此控件的客户端 ID 接收一个前缀,它是命名容器的 ID。使用 JavaScript,它很容易解决:
var elm = document.querySelector('[id$="lbl"]');
$= means, ends with.
$= 表示,以。
回答by Pieriv
Using getElementById
didn't work for me. The following can be used instead:
使用getElementById
对我不起作用。可以使用以下内容代替:
$find('<%=((Label)Master.FindControl("lbl")).ClientID %>');
回答by Maysam
回答by Vinay Bhardwaj
This is work for me:(Check the below code)
这对我有用:(检查下面的代码)
alert(document.getElementById('<%=(Master.FindControl("lbl")).ClientID %>').innerText);