This topic created in 3590 days ago, the information mentioned may be changed or developed.
function oneMenu() {
var main = document.getElementById("oneMenu");
var links = main.getElementsByClassName("cc-tree-item");
for (var i = 0; i < links.length; i++) {
links[i]. onclick = function () {
addClass(this, "cc-selected cc-focused")
}
}
}
想在点击一个元素时,删除其他同级元素的 "cc-selected cc-focused" class 。现在点击能追加样式,可不能删除
13 replies • 2016-07-19 13:46:40 +08:00
 |
|
1
xjp Jul 18, 2016
``` links[i]. onclick = function () { addClass(this, "cc-selected cc-focused") }; ```
这里的 this 指向的是全局 而不是你希望的 links[i],这里弄个闭包吧
|
 |
|
3
adv007 Jul 18, 2016 via iPhone
实现这种完全不需要遍历元素啊,楼主在动动脑子。你只需要记录一个当前高亮节点,并且在单击的时候重新指向新的当前节点
|
 |
|
4
YuJianrong Jul 18, 2016 via iPhone
1 , 2 楼确定?我记得时间处理函数的 this 就是 node 元素, lz 用法并没有问题。
|
 |
|
6
sjw199166 Jul 18, 2016
因为你没有清除 ;你在上面加一行 清楚所有那个的样式
|
 |
|
7
sjw199166 Jul 18, 2016
links[i]. onclick = function () { //这个去除所有的按钮样式 addClass(this, "cc-selected cc-focused") }
|
 |
|
8
iTakeo Jul 18, 2016 via iPhone
这里的 this 并没有问题
|
 |
|
10
LancerComet Jul 18, 2016
没有删除样式的代码
楼主可以递归 this 的 previousElementSibling 跟 nextElementSibling ,或者找 parentNode 的 children
|
 |
|
11
rain0002009 Jul 18, 2016
点击高亮么? 只要结构好 js 都不用写 纯 css+html 的 radio 标签就可以实现
|
 |
|
12
yiyizym Jul 18, 2016
links[i]. onclick = function () { //先删除所有 [].slice.call(links).forEach(function(link){link.classList.remove('cc-selected', 'cc-focused')}); addClass(this, "cc-selected cc-focused") }
|