我有此代码:
function showAll(el){
var id = el.parentNode.id;
var all= document.getElementById(id).getElementsByClassName('items')[0];
if(all.style.display === 'block'){
all.style.display = 'none';
} else{
all.style.display = 'block';
window.addEventListener('mouseup', function(e){
document.getElementById('test').innerHTML = e.target.className;
if(e.target != all){
all.style.display = 'none';
}
});
}
}
<div id="parent">
<div class="selected" onClick="showAll(this);">
</div>
<div class="items" style="display: none">
</div>
</div>
我基本上想要实现的是:单击selected
以显示items
,如果再次单击selected
或单击{{1 }}(该页面甚至items
上的一个随机位置)我希望能够隐藏selected
。
问题是,当我单击items
时没有EventListener
时,它可以显示selected
,然后如果我再次单击items
时,它可以隐藏{{ 1}},但是如果我点击随机点,则无法关闭selected
。
但是,当我添加items
并单击items
时,它可以单击一个随机点来关闭EventListener
,但是再次单击selected
却无法工作关闭items
。
请问有人可以帮我提供完整的JavaScript解释吗?
答案 0 :(得分:1)
您将要使用高度可重用的代码。我一直在自己的Web平台上使用change()
和id_()
,它非常直接和简单。在下面的示例中,第二个参数将使类为空(您也可以将id_('items').removeAttribute('class')
用于更简洁的DOM(文档对象模型))。
HTML
<input onclick="change(id_('items','');" type="button" value="Display Items" />
<div clas="hidden" id="items"><p>Items here.</p></div>
CSS
.hidden {display: none;}
JavaScript
function change(id,c)
{
if (id_(id)) {id_(id).className = c; if (id_(id).className=='') {id_(id).removeAttribute('class');}}
else if (id) {id.className = c; if (id.className=='') {id.removeAttribute('class');}}
else {alert('Error: the class id \''+id+'\' was not found or has not yet been imported to the DOM.\n\nNew class intended: '+c);}
}
function id_(id)
{
if (id == '' && window['console']) {console.log('Developer: empty id called from: '+id_.caller.toString().split('function ')[1].split('(')[0]);}
return (document.getElementById(id)) ? document.getElementById(id) : false;
}
该代码源于多年以来对同一平台的完善,而不是无意义改变事物的行业标准戏剧。从个人资料链接中的平台JavaScript文档中找到更具高度可重用性的函数,您只需单击两次即可。