日期:2014-05-16  浏览次数:20409 次

怎样 js 动态添加id
代码如下:<ul><li id="action"><a href="#">首页</a></li><li><a href="#">文章</a></li><li><a href="#">地址</a></li></ul>
在CSS中我会对此id进行注释,我想实现当我点击连接时,会把那个id动态添加到我所点击的那个li中,请问怎么实现这个效果……

------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
#action { background-color:red; }
</style>
</head>

<body>
<ul>
    <li id="action"><a href="#">首页</a></li>
    <li><a href="#">文章</a></li>
    <li><a href="#">地址</a></li>
</ul>

<script type="text/javascript">
var links = document.getElementsByTagName('ul')[0].getElementsByTagName('a');
for (var i = 0; i < links.length; i ++) {
    links[i].onclick = function() {
        for( var j = 0; j < links.length; j ++) links[j].parentNode.id = null;
        this.parentNode.id = 'action';
    }
}
</script>
</body>
</html>

------解决方案--------------------
动态设置class的代码:

HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
li.action { background-color:blue; }
</style>
</head>

<body>
<ul>
    <li><a href="#">首页</a></li>
    <li><a href="#">文章</a></li>
    <li><a href="#">地址</a></li>
</ul>

<script type="text/javascript">
var links = document.getElementsByTagName('ul')[0].getElementsByTagName('a');
for (var i = 0; i < links.length; i ++) {
    links[i].onclick = function() {
        for( var j = 0; j < links.length; j ++) links[j].parentNode.className = null;
        this.parentNode.className = 'action';
    }
}
</script>
</body>
</html>