2 回答
TA贡献1775条经验 获得超8个赞
我会稍微更改您的 html,以便您可以使用链接的 href 属性,然后只有一个函数来显示和隐藏相关的 div,而不是每个链接的函数(js 中的注释解释了我所做的事情):
var divs = document.getElementsByClassName('details_object'); // get all the detail divs
var buttons = document.getElementsByTagName('a'); // get all the links
for (var i = 0, len = buttons.length; i < len; i++) {
buttons[i].addEventListener("click", function(e) { // bind your click to the buttons (pass the event into the function)
e.preventDefault(); // stop the default click event of the anchor
for (var j = 0; j < divs.length; j++) {
if (divs[j].id === e.currentTarget.hash.substr(1)) { // compare the id of the div with the hash value of the link href (minus the #)
divs[j].style.display = 'block'; // if they match - show the div
buttons[j].classList.add('highlight');
} else {
divs[j].style.display = 'none'; // if they don't match - hide the div
buttons[j].classList.remove('highlight');
}
}
});
};
.highlight {
background: green;
}
<header class="container">
<nav class="navbar">
<a id="1" href="#description">Description</a>
<a id="2" href="#benefits">Benefits</a>
</nav>
</header>
<div class="details">
<div class="details_object" id="description" style="display: none">
description
<p> <span></span> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo, dolorem. </p>
<p> <span></span> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo, dolorem. </p>
</div>
<div class="details_object" id="benefits" style="display: none">
benefits
<p> <span></span> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo, dolorem. </p>
<p> <span></span> Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo, dolorem. </p>
</div>
</div>
TA贡献1796条经验 获得超10个赞
您可以使用 Javascript 的innerHTML属性使其更优化和更容易。您可以从此处了解更多信息。
function myFunction1 (num) {
document.getElementById("description").innerHTML= "Description paragraph";
}
function myFunction2 (num) {
document.getElementById("description").innerHTML= "Benefits paragraph";
}
function myFunction (button) {
var x = button.id;
switch (x) {
case '1':
myFunction1(x);
break;
case '2':
myFunction2(x);
break;
default:
return false;
}
}
var buttons = document.getElementsByTagName('a');
for (var i = 0, len = buttons.length; i < len; i++) {
buttons[i].onclick = function (){
myFunction (this);
}};
<header class="container">
<nav class="navbar">
<a id="1">Description</a>
<a id="2">Benefits</a>
</nav>
</header>
<div class="details">
<div class="details_object" id="description"/>
<div class="details_object" id="benefits" />
</div>
添加回答
举报