我有以下html结构。当有人单击“切换” div 时,我想向内容 div 和分支 ul 兄弟添加一个隐藏类。再次单击时,我想删除它们。我可以写点击事件,但是我不知道如何从点击事件中引用嵌套内容和分支。
<ul id="tree">
<li class="leaf">
<div class="switch"></div>
<div class="content">
... stuff
</div>
<ul class="branch">
<li class="leaf">
<div class="switch"></div>
<div class="content">
... stuff
</div>
<ul class="branch">
<!-- Can be many layers deep -->
</ul>
</li>
</ul>
</li>
<li class="leaf">
<div class="switch"></div>
<div class="content">
... stuff
</div>
<ul class="branch">
<li class="leaf">
<div class="switch"></div>
<div class="content">
... stuff
</div>
<ul class="branch">
<!-- Can be many layers deep -->
</ul>
</li>
</ul>
</li>
<!-- Can be many more of these -->
</ul>
Javascript
var Library = (function () {
"use strict";
/**
* Create click events for all classes passed in.
*
* This is used by newer browsers that have getElementsByClassName.
*
* @param {array} class_names The class names to attatch click events to.
* @param {function} The callback to handle the click event.
*
* @return void
*/
var classNameClick = function(class_names, clickEvent) {
for(var i = 0; i < class_names.length; i++) {
var elements = document.getElementsByClassName(class_names[i]);
for(var j = 0; j < elements.length; j++) {
elements[j].onclick = clickEvent;
}
}
};
/**
* Loops through all DOM elements to find classes to attatch click events to.
*
* This is used by older browsers that don't have getElementsByClassName
*
* @param {array} class_names The class names to attatch click events to.
* @param {function} The callback to handle the click event.
*
* @return void
*/
var classTagClick = function(class_names, clickEvent) {
var elements = document.getElementsByTagName("*");
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
for(var j = 0; j < class_names.length; j++) {
if(element.className.indexOf(class_names[j]) >= 0) {
element.onclick = function() {
clickEvent();
}
}
}
}
};
return {
/**
* Loops through all DOM elements to find classes to attatch click events to.
*
* @param {array} class_names The class names to attatch click events to.
* @param {function} The callback to handle the click event.
*
* @return void
*/
classClick : function(class_names, clickEvent) {
if (typeof document.getElementsByClassName !== "undefined") {
classNameClick(class_names, clickEvent);
} else {
classTagClick(class_names, clickEvent);
}
}
};
}());
var Tree = (function () {
"use strict";
return {
construct : function () {
Library.classClick("switch", function() {
// Not sure how to reference the relevant content and branch class here.
});
}
};
}());
window.onload = function() {
Tree.construct();
}
我不能使用 jQuery 或其他库(使用 jQuery 很容易)。