使用 JavaScript 设置 HTML 属性
我下面有一个导航栏,
<div id="cmenu" class="cmenu r">
<div id="help"><a onClick="topMenu('help','current')" href="javascript:void(0)"><span>Help</span></a></div>
<div id="refer"><a onClick="topMenu('refer','current')" href="javascript:void(0)"><span>Refer Friends</span></a></div>
<div id="home"><a onClick="topMenu('home','current')" href="javascript:void(0)"><span>Home</span></a></div>
</div>
我想在单击链接时将 div 元素中的“class”属性设置为“current”。所以,我可以在 div/link 上指定新样式。这是我的功能:
function topMenu(id,prNode){
var topMenu=document.getElementById("cmenu").getElementsByTagName("div");
for (var a in topMenu){topMenu[a].removeAttribute("class");} //remove all "current" class (third line)
document.getElementById(id).setAttribute("class",prNode);} //set the new div class as "current" (last line)
但是,不幸的是。我的函数的最后一行不起作用...然后我尝试将最后一行更改为
alert("alert message");
它也不起作用... 但是,当我评论函数的第三行时,最后一行正在工作......第三行有任何错误语法吗?......
I have a navigation bar below
<div id="cmenu" class="cmenu r">
<div id="help"><a onClick="topMenu('help','current')" href="javascript:void(0)"><span>Help</span></a></div>
<div id="refer"><a onClick="topMenu('refer','current')" href="javascript:void(0)"><span>Refer Friends</span></a></div>
<div id="home"><a onClick="topMenu('home','current')" href="javascript:void(0)"><span>Home</span></a></div>
</div>
I'd like to set "class" attribute to "current" in div element when the link is clicked. so, I can specify a new style on the div/link.here is my function:
function topMenu(id,prNode){
var topMenu=document.getElementById("cmenu").getElementsByTagName("div");
for (var a in topMenu){topMenu[a].removeAttribute("class");} //remove all "current" class (third line)
document.getElementById(id).setAttribute("class",prNode);} //set the new div class as "current" (last line)
but, unfortunately. the last line of my function doesn't work... then I try to change the last line to
alert("alert message");
it also doesn't work...
but, when I commented the third line of my function, the last line is working.... is there any error syntax on the 3rd line?...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像数组一样遍历nodeList(而不是像对象)
如果像对象一样遍历它,您还将获得nodeList的属性“length”,这会导致错误。
walk the nodeList like an array(not like an object)
If you walk it like an object, you'll also get the property "length" of the nodeList, what results in an error.
setAttribute
在旧版本的 Internet Explorer 中严重损坏,请勿使用它。为映射到属性的 DOM 属性赋值(并读取而不是使用 getAttribute)。在本例中,
className
:另外,不要使用
for in
来遍历数组和类似数组的对象。for in
遍历对象的所有属性,而不仅仅是编号的属性。setAttribute
is horribly broken in older versions of Internet Explorer, don't use it. Assign values to (and read from instead of usinggetAttribute
) the DOM properties that map to attributes instead.In this case,
className
:Also, don't use
for in
to walk arrays and array-like objects.for in
walks all the properties of an object, not just numbered ones.