我正在使用 asp.net 与 c# 和 javascript。 我有一个母版页和许多使用它的 aspx 页面。 在母版页上,我有一个无序列表,它实际上是一个菜单。
无序列表具有 ID 和 runat ="server"
。问题是当我将 "runat ="server""
放在无序列表上时。我收到错误:“Microsoft JScript 运行时错误:无法获取属性“getElementsByTagName”的值:对象为 null 或未定义。”
它指向用于该功能的 script.js菜单的。特别是在一行:........
a=c; var w=document.getElementById(p), s=w.getElementsByTagName('ul'), l=s.length, i=0;
在母版页的头部,脚本的调用方式如下:
<script type="text/javascript" src="script.js">
</script>
script.js完整代码:
var menu=function(){
var t=15,z=50,s=6,a;
function dd(n){this.n=n; this.h=[]; this.c=[]}
dd.prototype.init=function(p,c){
a=c; var w=document.getElementById(p), s=w.getElementsByTagName('ul'), l=s.length, i=0;
for(i;i<l;i++){
var h=s[i].parentNode; this.h[i]=h; this.c[i]=s[i];
h.onmouseover=new Function(this.n+'.st('+i+',true)');
h.onmouseout=new Function(this.n+'.st('+i+')');
}
}
dd.prototype.st=function(x,f){
var c=this.c[x], h=this.h[x], p=h.getElementsByTagName('a')[0];
clearInterval(c.t); c.style.overflow='hidden';
if(f){
p.className+=' '+a;
if(!c.mh){c.style.display='block'; c.style.height=''; c.mh=c.offsetHeight; c.style.height=0}
if(c.mh==c.offsetHeight){c.style.overflow='visible'}
else{c.style.zIndex=z; z++; c.t=setInterval(function(){sl(c,1)},t)}
}else{p.className=p.className.replace(a,''); c.t=setInterval(function(){sl(c,-1)},t)}
}
function sl(c,f){
var h=c.offsetHeight;
if((h<=0&&f!=1)||(h>=c.mh&&f==1)){
if(f==1){c.style.filter=''; c.style.opacity=1; c.style.overflow='visible'}
clearInterval(c.t); return
}
var d=(f==1)?Math.ceil((c.mh-h)/s):Math.ceil(h/s), o=h/c.mh;
c.style.opacity=o; c.style.filter='alpha(opacity='+(o*100)+')';
c.style.height=h+(d*f)+'px'
}
return{dd:dd}
}();
无序列表菜单在form1内声明:
这是列表菜单代码:.
<ul class="menu" id="menu" runat ="server">
<li>
<a href="#" class="menulink">Mant</a>
<ul>
<li><a href="Mant.aspx">Table</a></li>
</ul>
</li>
</ul>
在 form1 之外,声明如下:
<script type="text/javascript">
var menu = new menu.dd("menu");
menu.init("menu", "menuhover");
</script>
除了 script.js 之外,所有代码都在母版页上声明。
我该如何解决这个问题?
谢谢...
帖子已编辑。
最佳答案
您没有提供足够的代码来给出具体答案,但我的预感如下......
默认情况下,ASP.Net 会更改包含 runat="server"
的元素的 ID以确保所有 ID 都是唯一的。您有两个选择:
向 ASP.Net 询问 JS 中的客户端 ID:
var clientID = "<%= txtUsername.ClientID %>";
看看
ClientIDMode
property 。将其设置为Static
,至少对于有问题的元素应该可以解决问题。
此错误也可能是在页面完全渲染之前执行 JS 导致的。同样,您没有提供足够的代码供我们做出此决定。
关于javascript - asp.net,javascript,无法获取属性 getElementsByTagName 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901529/