Reference ASP.NET control by ID in JavaScript?

前端 未结 9 1221
孤街浪徒
孤街浪徒 2020-11-28 09:25

When ASP.NET controls are rendered their ids sometimes change, like if they are in a naming container. Button1 may actually have an id of ctl00_ContentMai

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 10:24

    Couple of thoughts on this:

    1) I've had a lot of luck getting elements by css class instead of id because asp.net ids are not reliable as you stated. I use this function and it performs reasonably well:

    function getElementsByClass(searchClass,node,tag) {
     var classElements = new Array();
     if ( node == null )
        {
            node = document;
        }
    
     if ( tag == null )
        {
            tag = '*';
        }
    
     var els = node.getElementsByTagName(tag);
     var elsLen = els.length;
     var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    
     for (i = 0, j = 0; i < elsLen; i++) 
        {
            if ( pattern.test(els[i].className) ) 
                {
                    classElements[j] = els[i];
                    j++;
                }
          }
     return classElements;
    }
    

    2) jQuery helps here alot. Using jQuery you can reliably get elements where the id ends with a certain string. While this is not "the" reason to use jQuery it's definitely a plus.

    3) This will be fixed in asp.net 4.0 so hang in there :-) http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

提交回复
热议问题