1

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

4

1 回答 1

1

您在单击事件上调用函数 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>
于 2013-07-02T11:13:28.907 回答