<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body,html {margin: 0;padding: 0;}
nav {width: 100px;height: 25px;border: 1px solid rosybrown;color: #fff;float: left;text-align: center;line-height: 25px;}
</style>
<script type="text/javascript">
window.onload = function() {
var arr = [{
title: "科技",
bgcolor: "blue",
currentbg: "block",
hash: "keji"
}, {
title: "军事",
bgcolor: "blue",
currentbg: "yellow",
hash: "junshi"
}, {
title: "新闻",
bgcolor: "blue",
currentbg: "red",
hash: "xinwen"
}];
var adom = [];
for (var attr in arr) {
if (!arr.hasOwnProperty(attr) || ("title" in arr[attr] && arr[attr]["title"] !== "")) {
var oNav = document.createElement("nav");
oNav.innerHTML = arr[attr]["title"];
oNav.style.backgroundColor = arr[attr]["bgcolor"];
oNav.setAttribute("data-hash", arr[attr]["hash"]);
document.querySelector("body").appendChild(oNav);
adom.push(oNav);
oNav.onclick = function() {
var hash = this.dataset.hash; //获取hash
window.location.hash = hash; //传给url
for (var j in adom) {
adom[j].style.backgroundColor = arr[j]["bgcolor"];
}
//我这里想获取当前选中状态下他对应的背景颜色在arr下的currentbg下
//比如我当前选中状态是第2个nav对应的就是this.style.backgroundColor="yellow"
this.style.backgroundColor = ;
};
window.onhashchange = function() { //url发现改变页面跟着变
hashchange();
}
hashchange();
function hashchange() {
var firstHash = window.location.hash.substring(1) || "";
for (var key in arr) {
document.querySelector("." + arr[key]["hash"]).style.display = "none";
}
if (firstHash) {
document.querySelector("." + firstHash).style.display = "block";
}
};
}
}
}
</script>
</head>
<body>
<p data-hash="keji" class="keji">科技版块</p>
<p data-hash="junshi" class="junshi" style="display: none;">军事版块</p>
<p data-hash="xinwen" class="xinwen" style="display: none;">新闻版块</p>
</body>
</html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果我没理解错,你想在事件处理器里面访问循环中的变量arr,但是当你的循环执行完了,你的事件处理器真正触发是在循环执行完之后,attr已经变成了最后一个。
看下我评论里面给你提供的那个链接吧。。。
使用闭包缓存临时变量吧