insertAfter基于ID的特定元素 [英] insertAfter specific element based on ID
问题描述
我有两个链接列表。我有它,当用户点击任一列表上的链接时,它将被移动到另一个列表。很快这些列表变得无组织,所以我想用ID来组织它们。
I have two lists of links. I have it such that when a user clicks on a link on either list, it is moved to the other list. Very quickly the lists become unorganised so I would like to keep them organised by an ID.
我想要的是当用户点击链接时,它会在 data-id
的最后一个元素的列表小于单击的链接。之后我会插入元素。
What I want then is when a user clicks the link, it will search in the list for the last element whose data-id
is less than the link that was clicked. I would then insert the element after that.
现在,我真正感兴趣的是使用jQuery实现这一点的最有效(代码方式)方式。我知道我可以使用 $(。added)。each()
来做到这一点,但它看起来非常笨重。是否有更好的方式使用选择器或其他东西?
Now, what I am really interested in is the most efficient (code wise) way of doing this with jQuery. I understand I can do this using $(".added").each()
but it seems very clunky. Is there a better way using selectors or something else?
<div class="available">
<h2>Available Groups</h2>
<a href="" data-id="1">Group 1<span>Add</span></a>
<a href="" data-id="2">Group 2<span>Add</span></a>
<a href="" data-id="3">Group 3<span>Add</span></a>
<a href="" data-id="4">Group 4<span>Add</span></a>
<a href="" data-id="5">Group 5<span>Add</span></a>
</div>
<div class="added">
<h2>Added Groups</h2>
</div>
当前实施:
$(".available a").on("click",function(){
var myID = parseInt($(this).data("id"));
var alist = $(".added a");
if (alist.length > 0) {
var nodeToInsertAfter;
$(".added a").each(function () {
if (parseInt($(this).data("id")) < myID)
nodeToInsertAfter = $(this)
});
if (nodeToInsertAfter)
$(this).insertAfter(nodeToInsertAfter);
else
$(this).prependTo(".added");
}
else {
$(this).appendTo(".added");
}
});
推荐答案
以下是一种方式: jsFiddle示例
Here's one way: jsFiddle example
$(".available a").on("click", function(e) {
e.preventDefault();
$('.added h2').after($(this));
var items = $('.added a').get();
items.sort(function(a, b) {
var A = $(a).data('id');
var B = $(b).data('id');
if (A < B) return -1;
if (A > B) return 1;
return 0;
});
$('.added h2').after(items);
});
这篇关于insertAfter基于ID的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!