要在第一个中插入新的 div,您可以使用以下内容:
$( "#adv" ).append( createNewDiv( "foo" ) );
$( "#adv" ).append( createNewDiv( "bar" ) );
function createNewDiv( content ) {
var $div = $( '<div class="slide">' + content + '</div>' );
var $span = $( '<span class="separator"></span>' );
$div.append( $span );
return $div;
}
要转换您的代码,您可以使用以下内容:
cleanAndBuild( $( '#adv' ) );
function sliceIt( $divToSlide ) {
var html = $divToSlide.html();
var sliceStart = 0;
var i = 0;
var slices = [];
while ( true ) {
// getting the index to slice to.
var sliceEnd = html.indexOf( '</span>' ) + 7;
// -1 +7 (-1 not found, 7 of </span> size (in chars)
if ( sliceEnd == 6 ) {
break;
}
// inserting the new slice
slices.push( html.substring( sliceStart, sliceEnd ) );
// removing sliced piece
html = html.substring( sliceEnd, html.length );
}
return slices;
}
function cleanAndBuild( $divToCleanAndBuild ) {
// getting the slices...
var slices = sliceIt( $divToCleanAndBuild );
// cleaning the main container
$divToCleanAndBuild.html( "" );
// iterating over the slices, creating a new div, putting the slice inside it and
// appending it to the container
slices.forEach( function( el ) {
var $slideDiv = $( '<div class="slide"></div>' );
$slideDiv.append( el );
$divToCleanAndBuild.append( $slideDiv );
});
}