这不起作用:
<a onclick="if(document.getElementById('div2','div1') .style.display=='none') {document.getElementById('div2','div1') .style.display=''}else
{document.getElementById('div2','div1') .style.display='none'}">
this1 ~~
</a>
<div id="div1" style="display:none">
1
</div>
<a onclick="if(document.getElementById('div2') .style.display=='none') {document.getElementById('div2') .style.display=''}else
{document.getElementById('div2') .style.display='none'}">
this2 ~~
</a>
<div id="div2" style="display:none">
2
</div>
点击这个1 ~~时如何显示div2和div1?它只显示点击时的div2而不显示两者。为什么不起作用?
答案 0 :(得分:1)
JavaScript在HTML标记中没有位置。它应该保持独立。话虽如此,getElementById
只获得一个元素。你需要调用它两次以获得两个元素。
尝试这样的事情:
<a id="this1">this1 ~~</a>
<div id="div1" style="display:none">1</div>
<a id="this2">this2 ~~</a>
<div id="div2" style="display:none">2</div>
然后在<head>
中添加JavaScript:
// Make sure the page is ready
window.onload = function(){
// Save references to them, so we don't need to keep looking them up
var div1 = document.getElementById('div1'),
div2 = document.getElementById('div2');
// Add events to our <a> tags
document.getElementById('this1').addEventListener('click', function(){
// Toggle div1 and div2
if(div1.style.display === 'none' && div2.style.display === 'none'){
div1.style.display = div2.style.display = '';
}
else{
div1.style.display = div2.style.display = 'none';
}
});
document.getElementById('this2').addEventListener('click', function(){
// Toggle div2 only
if(div2.style.display === 'none'){
div2.style.display = '';
}
else{
div2.style.display = 'none';
}
});
};