javascript - 如果列表项 onClick 更改背景颜色并重置其他元素

标签 javascript css

for (const doc of docs) {
    // create a `div` element
    const div = document.createElement("li");
    div.classList.add("list-group-item");
    div.style.border = "none";

    // add a text node to it
    div.appendChild(document.createTextNode(doc.name));

    // add event listeners to change its background
    div.addEventListener("mouseover", e => { div.style.background = "#e9ecef"; });
    if (div.style.backgroundColor !== "#e9ecef") {
        div.addEventListener("mouseout", e => { div.style.background = "white"; });
    }
    // add a `click` listener
    div.addEventListener("click", e => {
        updateInput(doc);

        var listGroup = document.getElementById("list-group-row").getElementsByTagName('li');
    });

    // add the new div to the container
    container.appendChild(div);
}

这是一个循环,我将列表项添加到我的容器中。 mouseovermouseoutaddEventListener 提供了一种效果,当我们悬停时改变背景颜色,悬停时变回白色。

我的问题出在 addEventListener click 部分。 我试图更改 div.style.backgroundColor,但显然这会将其他列表项的颜色更改为,因为它在 for 循环内。

使单个列表项在单击时更改背景颜色并在单击其他项时更改回来的最佳方法是什么?

我还想保留 mouseovermouseout 效果。

完整代码:

    VSS.getService(VSS.ServiceIds.ExtensionData)
    // the callback on the next line returns a promise, which the JavaScript engine will follow, so you don't need to nest the next `then`
        .then((dataService) => dataService.getDocuments('MyCollection2'))
        .then((docs) => {
            // keep a reference to the element instead of searching for it in each loop.
            const container = document.getElementById('items');

            // this loop will remove any existing children
            while (container.firstChild !== null) {
                container.removeChild(container.firstChild);
            }

            // `for...of` is a simpler way to iterate over a collection
            for (const doc of docs) {
                // create a `div` element
                const div = document.createElement("li");
                div.classList.add("list-group-item");
                div.style.border = "none";

                // add a text node to it
                div.appendChild(document.createTextNode(doc.name));

                // add event listeners to change its background
                div.addEventListener("mouseover", e => { div.style.background = "#e9ecef"; });
                div.addEventListener("mouseout", e => { div.style.background = "white"; });

                // add a `click` listener
                //get all the elements with calss list-group-item
                [...document.querySelectorAll('.list-group-item')].forEach(function(item) {
                    // iterate and add event lstener to each of them
                    item.addEventListener('click', function(elem) {
                        // check if any element have a class active
                        // if so then remove the class from it
                        let getElemWithClass = document.querySelector('.clicked');
                        if (getElemWithClass !== null) {
                            getElemWithClass.classList.remove('clicked');
                            getElemWithClass.classList.add('unClicked')
                        }
                        //add the active class to the element from which click event triggered
                        item.classList.add('clicked')

                    })
                })


                // add the new div to the container
                container.appendChild(div);
            }
        });

最佳答案

您可能不需要在循环内附加事件。创建一个新函数来附加事件,但仅在循环完成时调用此函数它的执行取决于类 list-group-item

的元素的可用性

//get all the elements with calss list-group-item
[...document.querySelectorAll('.list-group-item')].forEach(function(item) {
  // iterate and add event lstener to each of them
  item.addEventListener('click', function(elem) {
    // check if any element have a class active
    // if so then remove the class from it
    let getElemWithClass = document.querySelector('.active');
    if (getElemWithClass !== null) {
      getElemWithClass.classList.remove('active');
    }
    //add the active class to the element from which click event triggered
    item.classList.add('active')

  })
})
.active {
  color: green;
  font-size: 24px;
}
<li class="list-group-item"> 1 </li>
<li class="list-group-item"> 2 </li>
<li class="list-group-item"> 3 </li>
<li class="list-group-item"> 4 </li>

关于javascript - 如果列表项 onClick 更改背景颜色并重置其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751679/

相关文章:

html - 该网站不会在 Kindle Fire HDX 等少数布局上向下滚动

html - 带有 svg 的对象标签填充了整个网页

html - 使用计算相对于宽度的动画持续时间?

javascript - 在js函数中定义一个变量然后在函数外使用它?

javascript - Bing map 版本 8。自定义缩放按钮

html - 定位图像以与背景无缝融合时出现问题

javascript - 使用 JS 自动更改 bg (css)(并缓慢过渡)

javascript - 删除脚本中的 HTML 标签

javascript - 侧边栏将幻灯片切换到右侧

javascript - 如何从 javascript 中的相同多个 div 类名获取特定值?