我有一个可以在 dom 中重新排列的单词列表,我需要按特定顺序抓取每个单词。 我已经(有点)计算了我需要它们的顺序,并使用jQuery使用该数字作为他们的Id。
我的问题是我如何从编号最低的 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 的环绕声跨度,所以我在抓住它们后无法真正重新排列它们,至少我不想这样做。
有什么想法吗?
先.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
});
:
尽量不要在 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
}
}