我具有一些功能,单击按钮后,这些元素将进行排序。在网站上,我有几个按钮负责对不同的元素进行排序。我的功能看起来像这样
const sort = () => {
var list = document.querySelector('.list');
console.log([...list.children]);
[...list.children]
.sort((a,b)=>a.querySelector('.video-count').innerText.replace(/,/g, '') - b.querySelector('.video-count').innerText.replace(/,/g, ''))
.map(node=>list.appendChild(node))
}
document.getElementById("video").addEventListener('click', sort);
如果我想对其他元素进行排序,则在上面的函数中,我只需要更改此元素a.querySelector('.video-count')
(添加新类)
这是我的HTML代码
<ul class="list">
<li class="channel-wrraper">
<div class="channel-statistic">
<div class="statistic-wrraper">
<span class="statistic-name">subscribers:</span>
<span class="subscirber-count">${subscriberCount}</span>
</div>
<div class="statistic-wrraper">
<span class="statistic-name">videos:</span>
<span class="video-count">${videoCount}</span>
</div>
<div class="statistic-wrraper">
<span class="statistic-name">views:</span>
<span class="veiw-count">${viewCount}</span>
</div>
</div>
</li>
</ul>
我该如何解决这个问题?
答案 0 :(得分:1)
使用函数生成器
const sort = (selector) => () => {
var list = document.querySelector('.list');
console.log([...list.children]);
[...list.children]
.sort((a, b) => a.querySelector(selector).innerText.replace(/,/g, '') - b.querySelector(selector).innerText.replace(/,/g, ''))
.map(node => list.appendChild(node))
}
document.getElementById("sub").addEventListener('click', sort('.subscriber-count'));
document.getElementById("video").addEventListener('click', sort('.video-count'));
document.getElementById("view").addEventListener('click', sort('.view-count'));
.as-console-wrapper{max-height:2em!important;}
<ul class="list">
<li class="channel-wrraper">
<div class="channel-statistic">
<div class="statistic-wrraper">
<span class="statistic-name">subscribers:</span>
<span class="subscriber-count">50</span>
</div>
<div class="statistic-wrraper">
<span class="statistic-name">videos:</span>
<span class="video-count">5</span>
</div>
<div class="statistic-wrraper">
<span class="statistic-name">views:</span>
<span class="view-count">1,000,000</span>
</div>
</div>
</li>
<li class="channel-wrraper">
<div class="channel-statistic">
<div class="statistic-wrraper">
<span class="statistic-name">subscribers:</span>
<span class="subscriber-count">5000</span>
</div>
<div class="statistic-wrraper">
<span class="statistic-name">videos:</span>
<span class="video-count">999</span>
</div>
<div class="statistic-wrraper">
<span class="statistic-name">views:</span>
<span class="view-count">500,000</span>
</div>
</div>
</li>
</ul>
<button id="sub">subs</button>
<button id="video">videos</button>
<button id="view">views</button>