从外部 javascript 文件中获取用户控件中的 clientid控件、文件、用户、javascript

2023-09-07 14:47:37 作者:我方水晶

我正在 ASP.NET 中开发一个用户控件 (ascx),它使用 javascript 来操作控件.目前,javascript 代码是内联的,并使用 <%= somecontrol.ClientID %> 来获取所需的控件.

I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.

我想将 javascript 文件放在外部文件中,但是从外部文件中我无法使用上述语法来检索控件.我在 这个和这个 回答,但问题是用户控件可以在页面上多次放置.这意味着 Controls 数组(在答案中提到)将使用不同的项目多次呈现.结果,脚本将无法检索它需要的 id.如果我将 <%= ClientId %> 放在包含项目的数组的名称中,那么我将遇到与我试图解决的问题相同的问题.

I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.

有什么想法吗?

推荐答案

好的,另一种方法,我尝试使用 JavaScript 类样式,然后为每个控件初始化它.

Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.

在外部 javascript 文件中,将代码编写为:

In the external javascript file, write your code as:

function oNameCls(ControlId1) {

    this.ControlId1 = ControlId1;

    this.DoYourWork1 = function() {
        // use the control id.
        // this.ControlId1
    }    
    this.DoYourWork2 = function() {
        // use the control id.
        // this.ControlId1
    }    

}

然后在控件上进行这样的调用.

And on the control do the call like that.

<script language="Javascript" type="text/javascript">
    // init - create
    var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
    // do your work
    <%=this.ClientID%>MyCls.DoYourWork1();
</script>

希望现在能提供更好的帮助.

Hope now help better.