【发布时间】:2017-01-28 01:35:41
【问题描述】:
此代码是常见问题解答的原始版本,包含三个答案,单击它时可以显示或隐藏。我的任务是修改为一次只显示一个答案(其他两个必须关闭)。 我得到一个提示,使用 for 循环遍历数组中的 h2 元素,并删除所有不是被点击的 h2 元素的 class 属性。 谢谢,
"use strict";
var $ = function(id) { return document.getElementById(id); };
// the event handler for the click event of each h2 element
var toggle = function() {
var h2 = this; // clicked h2 tag
var div = h2.nextElementSibling; // h2 tag's sibling div tag
// toggle plus and minus image in h2 elements by adding or removing a class
if (h2.hasAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "minus");
}
// toggle div visibility by adding or removing a class
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class", "open");
}
};
window.onload = function() {
// get the h2 tags
var faqs = $("faqs");
var h2Elements = faqs.getElementsByTagName("h2");
// attach event handler for each h2 tag
for (var i = 0; i < h2Elements.length; i++ ) {
h2Elements[i].onclick = toggle;
}
// set focus on first h2 tag's <a> tag
h2Elements[0].firstChild.focus();
};
【问题讨论】:
-
设计第一,代码第二!在设计中,您需要考虑诸如单击 h2 元素中的链接是否会导航到另一个页面、如果用户单击已打开的答案该怎么办、是否需要处理两个以上的 h2 元素以及是否那么,为什么
onload函数内的点击处理程序不能访问h2 元素的集合。祝你作业好运:) -
谢谢 :) 我会确保在编码之前写出伪代码))
标签: javascript arrays loops