首页 > 解决方案 > 将列表的子元素推送到数组

问题描述

<div class="button">
    <ul id='modes' class='flex-row-wrap'>
      <li class="list-btn"><a href="#">Btn1</a>
        <i class="favorite">
          <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="heart" class="svg-inline--fa fa-heart fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
            <path fill="currentColor" d="M462.3 62.6C407.5 15.9 326 24.3 275.7 76.2L256 96.5l-19.7-20.3C186.1 24.3 104.5 15.9 49.7 62.6c-62.8 53.6-66.1 149.8-9.9 207.9l193.5 199.8c12.5 12.9 32.8 12.9 45.3 0l193.5-199.8c56.3-58.1 53-154.3-9.8-207.9z"></path>
          </svg>
        </i>
      </li>
      <li class="list-btn"><a href="#">Button Text here is very long 2</a>
        <i class="favorite">
          <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="heart" class="svg-inline--fa fa-heart fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
            <path fill="currentColor" d="M462.3 62.6C407.5 15.9 326 24.3 275.7 76.2L256 96.5l-19.7-20.3C186.1 24.3 104.5 15.9 49.7 62.6c-62.8 53.6-66.1 149.8-9.9 207.9l193.5 199.8c12.5 12.9 32.8 12.9 45.3 0l193.5-199.8c56.3-58.1 53-154.3-9.8-207.9z"></path>
          </svg>
        </i>
      </li>
      <li class="list-btn"><a href="#">Button 3</a>
        <i class="favorite"> 
          <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="heart" class="svg-inline--fa fa-heart fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
            <path fill="currentColor" d="M462.3 62.6C407.5 15.9 326 24.3 275.7 76.2L256 96.5l-19.7-20.3C186.1 24.3 104.5 15.9 49.7 62.6c-62.8 53.6-66.1 149.8-9.9 207.9l193.5 199.8c12.5 12.9 32.8 12.9 45.3 0l193.5-199.8c56.3-58.1 53-154.3-9.8-207.9z"></path>
          </svg>
        </i>
      </li>

//JavaScript函数

function store() {
    var favItem = document.getElementsByClassName('favorite');
    var favorites =[];
    var fav = favItem.children;
    favorites.push(fav);
    console.log(favItem);
    console.log(favorites);
}
document.querySelectorAll(".favorite").forEach(item => {
    item.addEventListener("click", store);
});

我试图在单击图标时将每个列表项存储在一个数组中,并再次单击该图标从数组中删除。但我不知道如何选择列表图标中的子元素。

标签: javascriptarraysaddeventlistener

解决方案


推荐阅读