简体   繁体   English

通过javascript更改html元素属性不会更改外观

[英]Changing html element property via javascript does not change appearance

I have got a html page, with a navigation bar. 我有一个带有导航栏的html页面。 Ideally, once user select one option, that option background image would change. 理想情况下,一旦用户选择一个选项,该选项的背景图像就会改变。 However, I was not able to achieve that, by using javascript to dynamically change the list property. 但是,我无法通过使用javascript动态更改list属性来实现这一点。

The html: 的HTML:

<html>
<head>
<link href="includes/css/content.css" rel="stylesheet" type="text/css">
<script>
function select(id)
{
    alert(id);
    var list = document.getElementsByTagName('li');
    for(var i=0;i<list.length;i++)
    {
        list[i].class='random';
    }
    document.getElementById(id).class='selected';
}
</script>
</head>
<body>
<div id="mainContent">
            <div class = 'nav'>
                <ul>
                    <li class='selected' id='home' onClick="select(this.id)"><a href="#" ><span  style='color:gray'>Home</span></a></li>
                    <li id='system' onClick="select(this.id)"><a href="#" ><span  style='color:gray'>Systems</span></a></li>
                    <li id='temp' onClick="select(this.id)" ><a href="#"><span  style='color:gray'>Notification Template</span></a></li>

                </ul>
        </div>
</body>
</html>

And the css file looks like this: css文件如下所示:

.nav .selected a{
background-size:cover;
background: url(../images/nav.gif) no-repeat top;
color:white;
}

Is there something I am doing wrong here? 我在这里做错什么了吗?

The property class does not exist for HTMLElement. HTMLElement不存在该属性class Use className to set the css class. 使用className设置css类。

For a full list of properties - see http://www.w3schools.com/jsref/dom_obj_all.asp 有关属性的完整列表,请参见http://www.w3schools.com/jsref/dom_obj_all.asp

如果您以这种方式设置类,则需要使用.className [ https://developer.mozilla.org/en-US/docs/DOM/element.className ]

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

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