【问题标题】:pure javascript table sorting纯javascript表格排序
【发布时间】:2020-06-26 11:54:28
【问题描述】:

我正在构建一个动态表,我还需要对其进行排序,并且箭头与值相对应(如果正在排序,则升序或降序)如果值正在升序,则箭头将始终向上,如果值下降箭头向下,但也可以在单击相同的 th 时进行切换,当单击另一个元素时,箭头应与排序状态相对应。 我在这里尝试了一些东西,但它没有按应有的方式工作。

如果你们能帮助我,在此先感谢

https://jsfiddle.net/947xkevd/

const API = 'https://raw.githubusercontent.com/alex-cenusa/movies/master/movies.json';

async function getData() {
  try {
    let response = await fetch(API);
    if (response.status == 200) {
      let data = await response.json();
      return data;
    } else {
      throw new Error(response.status);
    }
  } catch (error) {
    console.log(error);
  }
}

getData().then((data) => {
  const KEY = data.data.key.forEach((key) => {
    const LEGEND_WRAPPER = document.querySelector('.color-code-wrapper');
    const UNIT_TYPE = key.type;
    const KEY_BTN = document.createElement('button');
    KEY_BTN.innerText = UNIT_TYPE;
    const KEY_BTN_COLOR = key.color;
    KEY_BTN.style.backgroundColor = KEY_BTN_COLOR;
    LEGEND_WRAPPER.appendChild(KEY_BTN);
  });

  const TABLE_WRAPPER = document.querySelector('.table-wrapper');

  let col = [];
  for (let i = 0; i < data.data.movies.length; i++) {
    for (let key in data.data.movies[i]) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }
  }
  let button_style = {
    "Comedy": "blue-button",
    "Thriller": "pink-button",
    "Alternative": "green-button",
    "Documentary": "red-button"
  }

  function mergeObjectValues(key, obj, tablecell) {
    let merge_string = [];
    let button;
    for (let i = 0; i < obj.length; i++) {
      if (merge_string.indexOf(obj[i][key]) == -1) {
        merge_string.push(obj[i][key]);
        if (key == 'type') {
          button = document.createElement('button');
          button.classList.add(button_style[obj[i][key]]);
          button.innerHTML = obj[i][key];
          tablecell.append(button);
        } else {
          merge_string.push(obj[i][key]);
          tablecell.innerHTML = obj[i][key];
        }
      }
    }
    return tablecell;
  }

  const table = document.createElement('table');
  let tr = table.insertRow(-1); // table row.

  for (let i = 0; i < col.length; i++) {
    let th = document.createElement('th'); // table header.
    th.setAttribute('class', 'sort-cta');
    th.innerHTML = col[i];
    tr.appendChild(th);

    const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
    const comparer = (idx, asc) => (a, b) =>
      ((v1, v2) => (v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)))(
        getCellValue(asc ? a : b, idx),
        getCellValue(asc ? b : a, idx)
      );

    th.addEventListener('click', () => {
      sort();
    });

    function sort() {
      const table = th.closest('table');
      Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
        .sort(comparer(Array.from(th.parentNode.children).indexOf(th), (this.asc = !this.asc)))
        .forEach((tr) => table.appendChild(tr));
    }
  }
  let col_key = {
    "Type/Use": "type",
    "Rental": "name"
  }
  for (let i = 0; i < data.data.movies.length; i++) {
    tr = table.insertRow(-1);

    for (let j = 0; j < col.length; j++) {
      let tabCell = tr.insertCell(-1);
      var tablecontent = data.data.movies[i][col[j]];

//          console.log(col);
//          console.log(tablecontent instanceof Array);
      if (tablecontent instanceof Array) {
        tabCell = mergeObjectValues(col_key[col[j]], tablecontent, tabCell);
      } else {
        tabCell.innerHTML = tablecontent;
      }

    }
  }

  TABLE_WRAPPER.appendChild(table);
  const sorLnk = document.querySelectorAll('.sort-cta');
  sorLnk.forEach((item) => {
    item.addEventListener('click', () => {
      [...item.parentElement.children].forEach((sib) => {
        sib.classList.remove('down');
        item.classList.add('down');
      });
    });
  });
});
.color-code-wrapper {
  display: flex;
  justify-content: space-around;
  align-items: center;
  max-width: 400px;
}

.title {
  font-weight: 600;
}

button {
  border: none;
  border-radius: 30px;
  padding: 4px 10px;
  text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
  color: #fff;
  font-weight: 600;
}

table {
  width: 100%;
  margin: 32px 0;
}

tr {
  text-align: left;
  border-bottom: 1px solid #dddddd;
}

tr:first-of-type {
  border-bottom: 1px solid #333;
}

th {
  padding: 8px 0;
}

td {
  padding: 8px 0;
  font-size: 1.4rem;
}

.blue-button {
  background-color: rgb(64, 0, 255);
}

.pink-button {
  background-color: rgb(255, 0, 191);
}

.red-button {
  background-color: rgb(255, 0, 0);
}

.green-button {
  background-color: rgb(0, 255, 64);
}

.sort-cta {
  cursor: pointer;
  border: none;
  text-transform: capitalize;
  background-color: transparent;
}

.sort-cta:after {
  content: '\25b2';
  margin: 0 4px;
  font-size: 12px;
}

.sort-cta.down:after {
  content: '\25BC';
}


}
<div class="available-movies-component">
  <div class="color-code-wrapper">
    <span class="title">Key</span>
  </div>

  <div class="table-wrapper">

  </div>
</div>

【问题讨论】:

  • 究竟是什么不工作?请具体并给出逐步重现的方法
  • 我想要实现的是,对于每个表头选项,当我第一次单击它时,数据将按升序(向上箭头)排序,并且只有在我切换时才会降序(向下)相同的选项。如果我第一次单击标题选项,数据将升序,然后如果我单击单位选项,数据将升序。现在例如,如果我单击平铺选项,数据将上升,但箭头向下。

标签: javascript sorting css-tables


【解决方案1】:

在此处查看我的答案:Select and sort a column in a table using Javascript,或在此处:Position table rows according to their dataset value
您可以使用 css(搜索语法)添加、更改和删除箭头。

【讨论】:

  • 排序正常,箭头的行为与排序不对应
  • 我看到你已经“向上”了。 “下”呢?单击 col 时:设置“up”|“down”或切换(如果已经有“up”|“down”),并从兄弟姐妹中删除两者。希望这会有所帮助。
【解决方案2】:

我在这个函数中发现了一些问题。我修好了。

sorLnk.forEach((item) => {
    item.addEventListener('click', () => {
        [...item.parentElement.children].forEach((sib) => {
            if (sib != item)
                // here we should check the sibling not to be the item itself
                sib.classList.remove('down');
        });
        // and here we toggle the 'down' class
        if (item.classList.contains('down')) {
            item.classList.remove('down');
        } else {
            item.classList.add('down');
        }
    });
});

【讨论】:

  • 等待您的时间,但这似乎不起作用..
  • 它对我有用!清理缓存并再次检查。在 jsfiddle 中检查它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多