开发者

jquery swap content between two DOM elements

I have two span tags. I'd like to swap the content between them once the user clicks on one of them. If the user clicks once more, swap the content again and so on.

$(".sectionTitleText").livequery("click", function () {
        var editor = $(this).attr开发者_如何学C("data-edit-id");
        var viewer = $(this).attr("data-view-id");

        //Swap code
});


If both nodes are the only children of the same parent, just do this:

$('#parent').prepend($('#parent').children().last());

This should take whichever element is currently last, and make it first.

See http://jsfiddle.net/alnitak/wt4VZ/ for demo.

If that doesn't apply, try:

var el1 = $('#element1');
var el2 = $('#element2');
var tag1 = $('<span/>').insertBefore(el1); // drop a marker in place
var tag2 = $('<span/>').insertBefore(el2); // drop a marker in place
tag1.replaceWith(el2);
tag2.replaceWith(el1);

The idea here is that the two temporary spans just act as place holders into which the original elements will be dropped, without serialising or otherwise messing with those elements.

See http://jsfiddle.net/alnitak/bzKXn/ for a demo of that.


$(".sectionTitleText").livequery("click", function () {
        var editor = $("#span1");  //put your ids here
        var viewer = $("#span2");

        editorContent = editor.clone();
    viewerContent = viewer.clone();

    editor.replaceWith(viewerContent);
    viewer.replaceWith(editorContent);
});


Here's a generic jQuery function to do it:

$.fn.swapWith = function(swap_with_selector) {
    var el1 = this;
    var el2 = $(swap_with_selector);

    if ( el1.length === 0 || el2.length === 0 )
        return;

    var el2_content = el2.html();
    el2.html(el1.html());
    el1.html(el2_content);
};

See this jsFiddle for an example.


This is a simple content swapping.

var temp = $("#span1").html();
$("#span1").html($("#span2").html());
$("#span2").html(temp);


You need too keep the text in the span :

var firstText = $('#first_span_id').text()
var secondText = $('#second_span_id').text()

and then swap it :

$('#first_span_id').text(secondText)
$('#second_span_id').text(firstText)

If your span contains html tags, you may want to use .html() instead of .text()


I don't know what livequery is, but what about this:

function swapEditView(){
    var temp = $('#data-edit-id').html();
    $('#data-edit-id').html($('#data-view-id').html());
    $('#data-view-id').html(temp);
}

$('#data-edit-id').click(function(){
    swapEditView();
});

$('#data-view-id').click(function(){
    swapEditView();
});


You can create a temp object :

$element1 = $("#selector1");
$element2 = $("#selector2");

var $temp = $("<div>");
$element2.after($temp);
$element1.after($element2);
$temp.after($element1);
$temp.remove();

It's possible with before() too. It's possible because after() and before() move (or add) object in DOM, not duplicate it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜