问题
I have the following code,
<div id=1 class="mydiv"> <span>some data</span></div>
<div id="q-1">data</div>
<div id=2 class="mydiv"> <span>some data</span></div>
<div id="q-2">data</div>
<div id=3 class="mydiv"> <span>some data</span></div>
<div id="q-3">data</div>
<div id=4 class="mydiv"> <span>some data</span></div>
<div id="q-4">data</div>
<div id=5 class="mydiv"> <span>some data</span></div>
<div id="q-5">data</div>
I need to exchange a div of a given ID with the one after it, with the same class.
回答1:
To insert an element after another element using jQuery, use insertAfter. Note that it automatically removes the element from its original context:
Here, you want something like this:
$('#4').insertAfter('#5');
Note also that IDs cannot start with a number, unless you are using an HTML5 doctype.
To exchange with the next element, use next:
var $el = $('#4');
$el.insertAfter($el.next());
回答2:
Since judging by comments you only know the id="4"
portion, and ID selectors are very fast you can just use .insertAfter() to place it after the .next() sibling element, like this:
$("#4").insertAfter($("#4").next());
You can try it out here.
In the case of a more expensive selector, just cache it, like this:
var elem = $("#4");
elem.insertAfter(elem.next());
You can test that version here.
回答3:
Generic code for swapping two elements anywhere on the page:
$.fn.swapWith = function (selector) {
var placeholder = $('<div id="placeholder">').insertAfter(selector);
$(selector).insertAfter(this);
placeholder.after(this).remove();
};
Use like this:
$('#4').swapWith('#5');
You can use any valid jQuery selector/object in place of '#4' or '#5'. For your example you want:
var el = $('#4');
el.swapWith(el.nextAll('.' + el.attr('class') + ':first'));
回答4:
Let's say you know about the div with the id 5. So what you need to do is find the next div.
var myDiv = $("#5");
myDiv.next("div").insertBefore(myDiv);
You will want to make this more robust, because there might not be a next div, and you need to handle that situation, but this should get you on the right track.
来源:https://stackoverflow.com/questions/4906926/replacing-div-tag