单击其他后,javascript 删除元素样式

问题描述 投票:0回答:1

当单击其他 span 元素(不是同一 div)时,我尝试从 span 元素中删除属性“selected” div1 span swatch clickedanother div1 span swatch clicked

当div1另一个span被选中时,如何删除div_bottom1中span元素的“selected”属性?

<script type="text/javascript">
   window.addEventListener('DOMContentLoaded',() => {
      const div1 = document.getElementById('div1');
         div1.addEventListener('click', (e) => {
            const div1span = e.target.closest('span.swatch');
            if (!div1span) return;
            const dj = document.getElementById('div_bottom1');
            const djp = document.getElementById('div_bottom2');
            const dd = document.getElementById('div_bottom3');
   
         if (div1span.matches('.div1swatch')) {
            const clodj = dj.closest('span.selected');
            const clodd = dd.closest('span.selected');
            clodj.removeProperty('selected');
            clodd.removeProperty('selected');
         }
   });
</script>

它一直有效,直到获得

div1span.matches('.div1swatch')
,然后:

“未捕获类型错误:无法读取 null 的属性”错误

div 2-4 是 div1 之外的单独 div,并且在切换

div1span
时设置了 style.display = "none";

单击

div1span
style.display = "none";
设置为
div_bottom2
div_bottom3

单击

div2span
style.display = "none";
设置为
div_bottom1
div_bottom3

单击

div3span
style.display = "none";
设置为
div_bottom1
div_bottom2

有关系吗?

我做错了什么?我是 javascript 新手,目前正在使用 php + html 进行编码

html javascript

javascript deselect
1个回答
0
投票

存储在变量中

let elBoxSelected;
所选的item(元素)
为所有(!)您的框分配点击(不仅是
#div1
中的框)

let elBoxSelected;

document.querySelector("#boxes").addEventListener("click", (ev) => {
  const elBox = ev.target.closest(".box");
  
  if (!elBox) return; // Not a box clicked. Do nothing
  
  if (elBox !== elBoxSelected) {
    elBoxSelected?.classList.remove("selected");
    elBoxSelected = elBox;
  }
  
  elBoxSelected.classList.toggle("selected");

});
.row {
  display: flex;
  padding-bottom: 1rem;
  gap: 1rem;
  
  .box {
    display: inline-flex;
    border: 2px solid #000;
    width: 3rem;
    aspect-ratio: 1;
    
    &.selected {
      border-color: #0bf;
      
      &::after {
        margin: auto;
        content: "✓";
      }
    }
  }
}
<div id="boxes">
  <div class="row">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="row">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.