Switch positions of 2 divs with jQuery

后端 未结 6 1645
遥遥无期
遥遥无期 2020-12-02 22:45

I\'m wondering if it\'s posible to switch positions of two divs with jQuery.

I have two div like this

STUFF ONE
6条回答
  •  臣服心动
    2020-12-02 23:37

    I've found elegant jQuery plugin in 4 lines for that. Author Yannick Guinness.

    /**
     * Swap an element with another one
     * @author: Yannick Guinness
     * @version: 0.1
     *
     * @params {Object} element - object that has to be swapped
     * @return: {jQuery Object}
     *
     * @usage:
     *     $('.one').swap('.two');
     *
     * @license: MIT
     * @date: 2013/07/22
     **/
    $.fn.swap = function (elem) {
        elem = elem.jquery ? elem : $(elem);
        return this.each(function () {
            $(document.createTextNode('')).insertBefore(this).before(elem.before(this)).remove();
        });
    };
    
    $('.one').on('click', function () {
        alert(true);
    });
    
    $('input').click(function () {
        $('.one').swap('.two');
    });
    

    Run it in fiddle

    While @Vigront's answer simple and great (I've upvoted it), it has one serious drawback - on cloning elements loose events, bound to them...

    That plugin do not have such the problem. And even fiddle contains click event to demonstrate it.

提交回复
热议问题