我是一个JavaScript初学者,我的代码中出现了一个错误,谁能给我一些建议?
window.onload = function() {
value1.style.display = "block";
value2.style.display = "none";
value3.style.display = "none";
value4.style.display = "none";
}
if(window.localStorage.getItem('valuestate') === null) {
setValue ('value1');
value1.style.display = "block";
} else {
var valueItem = readValue()
document.getElementById('valueItem').style.display = "block";
}
function setValue (clickedOn) {
clearValue();
window.localStorage.setItem('valuestate', clickedOn);
document.getElementById(clickedOn).style.display = "block";
}
function clearValue () {
var value = document.getElementsByClassName('container');
for (var loop = 0; loop < value.length; loop++) {
value[loop].style.display = 'none';
}
}
function readValue () {
console.log( window.localStorage.getItem('valuestate') );
return window.localStorage.getItem('valuestate');
}
function doValue(clickedElement) {
setValue(clickedElement);
document.getElementById(clickedElement).focus();
}
HTML。
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item" id="menu1">
<a class="nav-link" href="#" onclick="doValue('value1')" accesskey="h">Profile<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" id="menu2">
<a class="nav-link" href="#" onclick="doValue('value2')" accesskey="s">Skills</a>
</li>
<li class="nav-item" id="menu3">
<a class="nav-link" href="#" onclick="doValue('value3')" accesskey="p">Projects</a>
</li>
<li class="nav-item" id="menu4">
<a class="nav-link" href="#" onclick="doValue('value4')" accesskey="x">Experiences</a>
</li>
</ul>
</div>
错在
var valueItem = readValue()
document.getElementById('valueItem').style.display = "block";
首先,不要使用名称为 js.js
. 它只是坏。
这应该可以解决你的问题。
var valueItem = readValue()
document.getElementById(valueItem).style.display = "block";
问题:
你传递的参数是 valueItem
"作为字符串 "到 document.getElementById()
这是一个变量。