点击动作具有两个功能:添加/删除类和切换属性值

时间:2019-07-10 20:18:12

标签: javascript

我正在处理带有嵌套锚链接的锚链接列表,并且想做几件事。

点击链接时:

  1. 添加“当前”类别
  2. 从任何其他链接或嵌套链接中删除“当前”类
  3. 如果该项目包含子项,请切换数据属性的值(即data-children =“ visible”或data-children =“ hidden”)
  4. 并且锚链接仍应工作

请注意,“ data-children”属性是在父a.link还是在div.children上对我来说都没有关系。

HTML

<ul>
    <li><a href="#l1" class="link">Level 1</a></li>
    <li><a href="#l2" class="link" data-children="hidden">Level 2</a>
        <div class="children">
            <ul>
                <li><a href="#l2-1" class="link">Level 2.1</a></li>
                <li><a href="#l2-2" class="link" data-children="hidden">Level 2.2</a></li>
                <li><a href="#l2-3" class="link">Level 2.3</a></li>
            </ul>
        </div>
    </li>
    <li><a href="#l3" class="link">Level 3</a></li>
</ul>

JavaScript

let el = document.querySelectorAll('.link');
for (let i = 0; i < el.length; i++) {
  el[i].onclick = function() {
    let c = 0;
    while (c < el.length) {
      el[c++].className = 'link';
    }
    el[i].className = 'link current';

    let x = el.getAttribute('data-children');
    if (x === 'visible') {
      el.setAttribute('data-children', 'visible');
    } else {
      el.setAttribute('data-children', 'hidden');
    }
  };
}

预期结果是允许任何链接成为“当前”链接,并能够将显示切换到任何或所有子链接。

单击父链接将添加class =“ link current”并将属性切换为data-children =“ visible”。再次单击父链接,会将属性切换为data-children =“ hidden”,该链接仍将具有class =“ link current”

1 个答案:

答案 0 :(得分:0)

尝试一下:

let el = document.querySelectorAll('.link');
    for (let i = 0; i < el.length; i++) {
        el[i].onclick = function() {
            let c = 0;
            while (c < el.length) {
            el[c++].className = 'link';
            }
            el[i].className = 'link current';
            
            // toggle data-children attribute for clicked link and childs
            var hidden_node = el[i].parentNode.querySelectorAll('[data-children=hidden]');
            var visible_node = el[i].parentNode.querySelectorAll('[data-children=visible]');

            for (let i = 0; i < hidden_node.length; i++) {
                hidden_node[i].setAttribute('data-children', 'visible');
            }

            for (let i = 0; i < visible_node.length; i++) {
                visible_node[i].setAttribute('data-children', 'hidden');
            }
        };
    }
<ul>
    <li><a href="#l1" class="link">Level 1</a></li>
    <li><a href="#l2" class="link" data-children="hidden">Level 2</a>
        <div class="children">
            <ul>
                <li><a href="#l2-1" class="link">Level 2.1</a></li>
                <li><a href="#l2-2" class="link" data-children="hidden">Level 2.2</a></li>
                <li><a href="#l2-3" class="link">Level 2.3</a></li>
            </ul>
        </div>
    </li>
    <li><a href="#l3" class="link">Level 3</a></li>
</ul>