0

我有一个可以在 dom 中重新排列的单词列表,我需要按特定顺序抓取它们中的每一个。我已经(有点)计算了我需要它们的顺序,并使用 jQuery 将该数字用作它们的 ID。

我的问题是如何从编号最低的 ID 开始并以最高编号结束它们中的每一个?

html 看起来像这样:

<span class="chosenword" id="577.9848041534424" style="position: absolute; top: 320px; left: 442.9999694824219px; z-index: 1;">Word!</span>

JS是这样的:

 $('.chosenword').each(function(){
   var position = $(this).position();
   var id = ((position.left) * (position.top));
   $(this).attr('id', id);
  var chosenword =  $(this).html();


   $('#chosenwords').append(chosenword);
   $('#chosenwords').append(" ");
    });

请注意,我实际上并没有抓取具有 Id 的环绕 Span,因此在抓取它们之后我无法真正重新排列它们,至少我不想这样做。

有任何想法吗?

4

2 回答 2

2

.sort()首先它们,然后.each()像​​你已经在做的那样循环:

$($('.chosenword').toArray().sort(function(a,b){return +a.id - b.id;})).each(function(){
   // your existing code here
});

或者,如果您缓存 jQuery 对象,您可以对其进行排序,这样您就不必在排序后创建另一个 jQuery 对象:

var $chosen = $('.chosenword');
[].sort.call($chosen, function(a,b){return +a.id - b.id;});
$chosen.each(function() {
    // your existing code here
});
于 2012-12-17T02:44:46.963 回答
1

2件事:

尽量不要在 id 处使用数字。一般来说,标识符以字母或下划线开头是最好的。

<div><span class="chosenword" order="1">Word 1</span> - 
<span class="chosenword" order="550">Word 550</span> - 
<span class="chosenword" order="57">Word 57</span>
</div> - 
<div id="chosenwords"></div>​

尝试对数组进行排序,然后在设置它们的顺序后遍历它们中的每一个

$('.chosenword').each(function(){
    var position = $(this).position();
    var order = ((position.left) * (position.top));
    $(this).attr('order', order);
});

$('.chosenword').sort(sortByOrderAttr).each(function() {
   var chosenword = $(this).html() + " - ";
    $('#chosenwords').append(chosenword);
});

function sortByOrderAttr(a, b) {
    var idA = parseInt($(a).attr('order'));
    var idB = parseInt($(b).attr('order'));
    if (idA < idB) {
        return -1;
    } else {
        return 1
    }
}​
于 2012-12-17T03:04:39.593 回答