简体   繁体   English

使用 JavaScript 设置 HTML 属性

[英]set HTML Attribute using JavaScript

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.单击链接时,我想在 div 元素中将“class”属性设置为“current”。 so, I can specify a new style on the div/link.here is my function:所以,我可以在 div/link.here 上指定一个新样式,这是我的功能:

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?...它也不起作用......但是,当我评论我的函数的第三行时,最后一行正在工作......第三行是否有任何错误语法?......

walk the nodeList like an array(not like an object)像数组一样遍历 nodeList(不像对象)

for (var a=0;a<topmenu.length;++a){topMenu[a].removeAttribute("class");}

If you walk it like an object, you'll also get the property "length" of the nodeList, what results in an error.如果你像一个对象一样走它,你也会得到 nodeList 的属性“长度”,这会导致错误。

setAttribute is horribly broken in older versions of Internet Explorer, don't use it. setAttribute在旧版本的 Internet Explorer 中严重损坏,不要使用它。 Assign values to (and read from instead of using getAttribute ) the DOM properties that map to attributes instead.将值分配给(并从中读取而不是使用getAttribute )映射到属性的 DOM 属性。

In this case, className :在这种情况下, className

function topMenu(id,prNode){
    var topMenu = document.getElementById("cmenu").getElementsByTagName("div");
    for (var i = 0; i < topMenu.length; i++) {
        topMenu[i].className = '';
    }
    document.getElementById(id).className = prNode;
}

Also, don't use for in to walk arrays and array-like objects.另外,不要使用for in来遍历数组和类似数组的对象。 for in walks all the properties of an object, not just numbered ones. for in遍历对象的所有属性,而不仅仅是编号的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM