本文介绍了参考ASP.NET中的JavaScript由ID控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET控件呈现它们的ID有时会改变,就像如果他们在一个命名容器。 Button1的实际上可能有一个id ctl00_ContentMain_Button1 时,它呈现出来,例如。

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_ContentMain_Button1 when it is rendered, for example.

我知道,你可以写你的JavaScript字符串在你的cs文件,获取该控件的clientID的并注入脚本到使用clientscript你的页面,但那里,你可以使用ASP从JavaScript直接参一控的方式。 NET阿贾克斯?

I know that you can write your JavaScript as strings in your .cs file, get the control's clientID and inject the script into your page using clientscript, but is there a way that you can reference a control directly from JavaScript using ASP.NET Ajax?

我发现,写一个函数递归解析DOM,发现包含我要的是不可靠的ID的控制,所以我一直在寻找一个最佳实践,而不是一个解决方法。

I have found that writing a function to parse the dom recursively and find a control that CONTAINS the id that I want is unreliable, so I was looking for a best practice rather than a work-around.

推荐答案

的想法这对夫妻:

1)我有很多的运气得到的元素通过CSS类,而不是ID,因为asp.net ID是不可靠的,你说。我用这个功能,它表现相当不错:

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的帮助这里很多。使用jQuery你可以可靠地获得内容,其中ID具有一定的字符串结尾。虽然这不是的理由使用jQuery的它绝对是一个加号。

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)将其固定在asp.net 4.0所以挂在那里:-) http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

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

这篇关于参考ASP.NET中的JavaScript由ID控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 04:47