日期:2014-05-16 浏览次数:20409 次
<!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的代码:
<!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>