insertAfter specific element based on ID

蹲街弑〆低调 提交于 2019-12-10 17:39:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!