JQuery - .append() doesnt move the rest of code
i've these div on my html page :
// CSS
.trackon{width:710px; height:26px; color:#CCCCCC; font-weight:bold; float:left;}
.trackoff{display:none;}
// HTML
<div class="trackon" id="trackline1">Line 1</div>
<div class="trackon" id="trackline2">Line 2</div>
<div class="trackon" id="trackline3">Line 3</div>
<div class="trackoff" id="trackline4">Line 4</div>
<div class="trackoff" id="trackline5">Line 5</div>
with my own function addTrack(1) i want to append开发者_运维百科 (for example) Line 5 between 1 and 2. so i make this function :
function addTrack(param) {
$("#trackline5").removeClass().addClass('trackon');
$("#trackline"+param).append($("#trackline5").html());
}
the problem is that this append doesnt move the other div down. That div (the one with Line 5) will displayed overlapped at the end of div with Line 1.
where im wrong? cheers
First, I think you want after()
or insertAfter()
(which places elements after one another) rather than append()
or appendTo()
(which places elements inside one another). Secondly, don't bother with html()
, just use the element itself:
function addTrack(param) {
$("#trackline5").removeClass().addClass('trackon')
.insertAfter("#trackline"+param);
}
.html()
returns the inner content of its selection, not the tag itself. So you're not getting your whole div appended, just the text contents.
Since you want to move the containers and not take #trackline5's content and add it to #trackline1, you'll need a different approach - by appending $("#trackline5").html()
, you're only appending its contents - not the container. You'd want to do something similar to the following:
function addTrack(param) {
// Get the original element
var $trackline5 = $('#trackline5');
// We need a copy
var $el = $trackline5.clone();
// Remove the original from the DOM
$trackline5.remove();
// Insert the new element after the specified one
$('#trackline' + param).after($trackline5);
}
HTH.
I'd do it this way which simply moves line 5.
function addTrack(param) {
$("#trackline5").removeClass('trackoff').addClass('trackon').after($("#trackline" + param));
}
精彩评论