我知道有更好的方法可以做到这一点,但出于学习目的,请帮助我。我有一个带有多个按钮和多个列表的HTML。我希望每个按钮在单击时隐藏/显示其下的列表。我想了解如何在JavaScript中执行此操作。这是我到目前为止的代码。无法发布完整的HTML,因为它有私人信息,但它看起来像这样。
<div id="conf" class="article">
<button>Education</button>
<ul>
<LI>2Sofic Groups a IMAR
<LI>2Theory and Operator Algebra
<LI>2 Geometric Group Theory
<LI> 4th annual meeting
<LI>2007: Co-organizer of
</ul>
</div>
<div id="conf" class="article">
<button>Education</button>
<ul>
<LI>2Sofic Groups a IMAR
<LI>2Theory and Operator Algebra
<LI>2 Geometric Group Theory
<LI> 4th annual meeting
<LI>2007: Co-organizer of
</ul>
</div>
<script>
var clickerbutton = document.getElementsByTagName("button");
var listEl = document.getElementsByTagName("ul");
//function to be run when event listener is fired
var onButtonClick = function() {
listEl[i].classList.toggle("hide");
}
//event listener
for (i = 0; i < clickerbutton.lenght; i++){
clickerbutton[i].addEventListener("click", onButtonClick);
}
</script>
感谢您的帮助和解释。
答案 0 :(得分:0)
您必须在回调函数引用中绑定函数参数。 请注意,bind函数的第一个参数设置“onButtonClick”函数的“this”参数(未使用)。
var onButtonClick = function(index) {
listEl[index].classList.toggle("hide")
}
for (i = 0; i < clickerbutton.length; i++){
clickerbutton[i].addEventListener("click", onButtonClick.bind(null, i));
}
答案 1 :(得分:0)
你必须像{mfranchi
那样使用.bind
var clickerbutton = document.getElementsByTagName("button");
var listEl = document.getElementsByTagName("ul");
var onButtonClick = function(index) {
listEl[index].classList.toggle("hide")
}
for (i = 0; i < clickerbutton.length; i++){
clickerbutton[i].addEventListener("click", onButtonClick.bind(null, i));
}
&#13;
.hide{
visibility: hidden;
}
&#13;
<div id="conf" class="article">
<button>Education</button>
<ul>
<LI>2Sofic Groups a IMAR
<LI>2Theory and Operator Algebra
<LI>2 Geometric Group Theory
<LI> 4th annual meeting
<LI>2007: Co-organizer of
</ul>
</div>
<div id="conf" class="article">
<button>Education</button>
<ul>
<LI>2Sofic Groups a IMAR
<LI>2Theory and Operator Algebra
<LI>2 Geometric Group Theory
<LI> 4th annual meeting
<LI>2007: Co-organizer of
</ul>
</div>
&#13;
答案 2 :(得分:0)
您可以根据样式属性“none”和“block”
显示/隐藏元素var clickerbutton = document.getElementsByTagName("button");
var listEl = document.getElementsByTagName("ul");
function findArrayIndex(arr,val)
{
for(var cnt=0;cnt<arr.length;++cnt)
{
if(arr[cnt] === val)
return cnt;
}
return -1;
}
var onButtonClick = function(e,ar)
{
var index = findArrayIndex(clickerbutton,this);
if(index !== -1 && listEl.length>index)
{
if(listEl[index].style.display ==='none')
{
listEl[index].style.display = 'block';
}
else
{
listEl[index].style.display = 'none';
}
}
}
//event listener
for (var i = 0; i <clickerbutton.length; i++)
{
clickerbutton[i].addEventListener("click", onButtonClick);
}