如何通过JavaScript访问位于用户控件中的ASP控件

时间:2022-09-02 12:23:07

Hi All,

I'm designing a user control, briefly it contains an asp:hiddenfield control, i'm going to access it via JavaScript function like this

我正在设计一个用户控件,简要说它包含一个asp:hiddenfield控件,我将通过这样的JavaScript函数访问它

function doAnyThing
{
    var myVar = document.getElementById("myHiddenFiled");
}

but when I trace my code I found myVar assigned to null, does it matter

但是当我追踪我的代码时,我发现myVar被指定为null,这是否重要

document.getElementById()

method is used in user control file (.ascx) or in regular (.aspx) file, taking into consideration it works in (.aspx) file correctly

方法用于用户控制文件(.ascx)或常规(.aspx)文件,考虑到它在(.aspx)文件中正常工作

2 个解决方案

#1


You had to set by ClientID the final id of your control, that will depend by the structure of your page. Try this:

您必须通过ClientID设置控件的最终ID,这将取决于您的页面结构。试试这个:

function doAnyThing
{
    var myVar = document.getElementById("<%= yourControlServerID.ClientID %>");
}

Obviously this function need to be placed in the .aspx file. I suggest you to switch to use a framework like jQuery, that allows you to retrieve controls by more sofisticate selectors. This case will be solved by:

显然,此函数需要放在.aspx文件中。我建议你切换到使用像jQuery这样的框架,它允许你通过更多的sofistic选择器来检索控件。这种情况将通过以下方式解决:

$("[id$=yourControlServerID]");

and you can place your javascript code even in an external .js file.

并且您甚至可以将javascript代码放在外部.js文件中。

#2


to simplify you can use either:

为了简化你可以使用:

JQuery

$("<%= yourControlServerID.ClientID %>"). ....

ASP.NET JavaScript annotation:

ASP.NET JavaScript注释:

var myVar = $get("<%= yourControlServerID.ClientID %>");

the ASP.NET JavaScript annotation code is the same as:

ASP.NET JavaScript注释代码与以下内容相同:

var myVar = document.getElementById("<%= yourControlServerID.ClientID %>")

#1


You had to set by ClientID the final id of your control, that will depend by the structure of your page. Try this:

您必须通过ClientID设置控件的最终ID,这将取决于您的页面结构。试试这个:

function doAnyThing
{
    var myVar = document.getElementById("<%= yourControlServerID.ClientID %>");
}

Obviously this function need to be placed in the .aspx file. I suggest you to switch to use a framework like jQuery, that allows you to retrieve controls by more sofisticate selectors. This case will be solved by:

显然,此函数需要放在.aspx文件中。我建议你切换到使用像jQuery这样的框架,它允许你通过更多的sofistic选择器来检索控件。这种情况将通过以下方式解决:

$("[id$=yourControlServerID]");

and you can place your javascript code even in an external .js file.

并且您甚至可以将javascript代码放在外部.js文件中。

#2


to simplify you can use either:

为了简化你可以使用:

JQuery

$("<%= yourControlServerID.ClientID %>"). ....

ASP.NET JavaScript annotation:

ASP.NET JavaScript注释:

var myVar = $get("<%= yourControlServerID.ClientID %>");

the ASP.NET JavaScript annotation code is the same as:

ASP.NET JavaScript注释代码与以下内容相同:

var myVar = document.getElementById("<%= yourControlServerID.ClientID %>")