我这个写法为什么没有效果?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>test</title>
</head>
<body>
<script>
window.onload=about_nav;
function showsection(id){
var section=document.getElementsByTagName("section");
for(var i=0; i<section.length; i++){
if(section[i].id == id){
section[i].style.display="block";
}else{
section[i].style.display="none";
}
}
}
function about_nav(){
var about_nav=document.getElementById("about_nav");
var about_navA=about_nav.getElementsByTagName("a");
for(var i=0; i<about_navA.length; i++){
var about_nav_href=about_navA[i].getAttribute("href");
var id=about_nav_href.split("#")[1];
about_navA[i].onclick = function(){
showsection(id);
return false;
}
}
}
</script>
<article>
<h1>About</h1>
<nav id="about_nav">
<ul>
<li><a href="#jay">Jay Skript</a></li>
<li><a href="#domsters">Domsters</a></li>
</ul>
</nav>
<section id="jay">
<h2>Jay Skript</h2>
<p>description...about Jay Skript.</p>
</section>
<section id="domsters">
<h2>Domsters</h2>
<p>description...about Domsters.</p>
</section>
</article>
</body>
</html>
about_nav函数正确的写法是下面这样,看不明白,请求解释一下:
function about_nav(){
var about_nav=document.getElementById("about_nav");
var about_navA=about_nav.getElementsByTagName("a");
for(var i=0; i<about_navA.length; i++){
var about_nav_href=about_navA[i].getAttribute("href");
var id=about_nav_href.split("#")[1];
about_navA[i].thislinkid=id;
about_navA[i].onclick = function(){
showsection(this.thislinkid);
return false;
}
}
}
------解决方案--------------------
about_navA[i].onclick = function(){alert(id)//增加这句你就明白了,输出的id都是domsters
showsection(id);
return false;
}
你这个设计到闭包问题,一下说不清楚。。
function about_nav(){
var about_nav=document.getElementById("about_nav");
var about_navA=about_nav.getElementsByTagName("a");
for(var i=0; i<about_navA.length; i++){
var about_nav_href=about_navA[i].getAttribute("href");
var id=about_nav_href.split("#")[1];
about_navA[i].thislinkid=id;//给对象增加自定义属性thislinkid存储id
about_navA[i].onclick = function(){