js按钮按班级堆叠

时间:2013-07-02 10:52:05

标签: javascript class sorting button

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 not onload?而且我也不知道为什么按钮出现在顶部。

1 个答案:

答案 0 :(得分:1)

您在click事件上调用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>