gpt4 book ai didi

javascript - js 按类在按钮上堆叠

转载 作者:行者123 更新时间:2023-11-28 02:08:41 25 4
gpt4 key购买 nike

http://jsfiddle.net/Ad7GV/19/

<div id="10" class="owoc">banan</div>
<div id="9" class="owoc">ananas</div>
<div id="8" class="owoc">fasola</div>
<div id="7" class="owoc">pomarancz</div>
<div id="6" class="owoc">winogrono</div>
<div id="5" class="owoc">ogorek</div>
<div id="4" class="owoc">mango</div>
<div id="3" class="owoc">seler</div>
<div id="2" class="owoc">cebula</div>
<div id="1" class="owoc">kiwi</div>

<button onclick="sortABC()">sortuj alfabetycznie</button>

var elements = document.getElementsByTagName('div');
var filtered = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].className === "owoc") {
filtered.push(elements[i]);
}
}
var sorted = filtered.sort(function (a, b) {
return a.innerHTML > b.innerHTML;
});

var parent = elements[0].parentNode;

for (i = 0; i < sorted.length; i++) {
parent.appendChild(sorted[i]);
}

谁能告诉我如何连接这个脚本来对列表进行排序 onclick 而不是 onload ?而且我也不知道为什么按钮出现在顶部。

最佳答案

您在点击事件上调用函数 sortABC(),但没有将其定义为函数。

http://jsfiddle.net/Ad7GV/20/

var sortABC = function(){
var elements = document.getElementById('elements').children;
var filtered = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].className === "owoc") {
filtered.push(elements[i]);
}
}
var sorted = filtered.sort(function (a, b) {
return a.innerHTML > b.innerHTML;
});

var parent = elements[0].parentNode;

for (i = 0; i < sorted.length; i++) {
parent.appendChild(sorted[i]);
}
}

为了不对按钮进行排序,您可以将排序后的元素包装在容器中,并仅检索该容器的子元素:

<div id = "elements">
<div id="10" class="owoc">banan</div>
<div id="9" class="owoc">ananas</div>
<div id="8" class="owoc">fasola</div>
<div id="7" class="owoc">pomarancz</div>
<div id="6" class="owoc">winogrono</div>
<div id="5" class="owoc">ogorek</div>
<div id="4" class="owoc">mango</div>
<div id="3" class="owoc">seler</div>
<div id="2" class="owoc">cebula</div>
<div id="1" class="owoc">kiwi</div>
</div>
<button onclick="sortABC()">sortuj alfabetycznie</button>

关于javascript - js 按类在按钮上堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17423670/

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