问题
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.
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.
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>
The current implementation:
$(".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");
}
});
回答1:
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);
});
回答2:
insertAfter is not good way, try this: http://api.jquery.com/appendTo/
来源:https://stackoverflow.com/questions/12161678/insertafter-specific-element-based-on-id