gpt4 book ai didi

javascript - 如何通过单击位于该 li 内部的跨度内的相应图标来删除
  • 或选中/取消选中
  • 转载 作者:行者123 更新时间:2023-11-28 16:52:46 25 4
    gpt4 key购买 nike

    我有这种情况,1- 我想删除一个带有两个图标的 li,它作为一个跨度在里面:一个是选中或取消选中相应的 li,另一个是删除那个 li。2- 我还想通过单击图标(选中图标)同时单击 li 来选中或取消选中该 li。

    我想通过将 addEventListener 放在 ul 中来处理事件委托(delegate),但我不知道如何在代码中执行此操作。我没有任何 JS 代码,我希望你能帮助我

    谢谢

    //delegation events 
    //1-how to remove the li by clicking in icon with a class 'cross'?
    //2-how to check or uncheck the li by clicking on the icon with a class 'check' and also by clicking in that li and showing or hiding the icon 'check'?

    ul.addEventListener ('click',function())


    //or by using the addEventListener in iconCross, how can I remove the li?
    // and by using the addEventListener in icon check, how can I check/uncheck the li by clicking on the icon and also on the li?

    const iconCross = document.querySelectorAll('.cross')

    iconCross.addEventListener('click',function())
    li{

    display:flex;
    align-content:center;
    justify-contnt:space-between;

    }
    <ul>
    <li>
    <span>
    <i class="check"></i>
    <i class="cross"></i>
    </span>
    </li>
    </ul>

    最佳答案

    您可以使用 remove() 从 DOM 中删除元素。在这里,您的 li 向上两层,必须使用 parentElement 获取引用,然后调用 remove()

    let withRemove = document.querySelectorAll('.with-remove .cross')

    withRemove.forEach(e => {
    e.addEventListener('click', function(e) {
    this.parentElement.parentElement.remove();
    });
    });

    const withClass = document.querySelectorAll('.with-class .cross')

    withClass.forEach(e => {
    e.addEventListener('click', function(e) {
    this.parentElement.parentElement.classList.add('hide');
    });
    });
    li {
    display: flex;
    align-content: center;
    justify-content: space-between;
    }

    .hide {
    display: none !important;
    }
    <ul class="with-remove">
    <li>
    <span>
    <i class="check">check1</i>
    <i class="cross">cross1</i>
    </span>
    </li>
    <li>
    <span>
    <i class="check">check2</i>
    <i class="cross">cross2</i>
    </span>
    </li>
    </ul>

    <ul class="with-class">
    <li>
    <span>
    <i class="check">check11</i>
    <i class="cross">cross11</i>
    </span>
    </li>
    <li>
    <span>
    <i class="check">check22</i>
    <i class="cross">cross22</i>
    </span>
    </li>
    </ul>

    关于javascript - 如何通过单击位于该 li 内部的跨度内的相应图标来删除 <li> 或选中/取消选中 <li>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58338415/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com