我只是在学习jQuery,遇到了一个困扰我的问题。我需要移动,添加&命名div而不影响内容。
我有一个固定宽度的WRAPPER div,里面有SECTION div。这就是它的样子:
<body>
<div id="whitewrap">
<div id="wrapper-1" class="wrapper">
<div class="clearfix">
<section id="block-1">
<h1>Title</h1>
<p>Some wonderful content.</p>
</section><!-- #block-1 -->
<section id="block-2">
<h1>Title</h1>
<p>Some wonderful content.</p>
</section><!-- #block-2 -->
<section id="block-3">
<h1>Title</h1>
<p>Some wonderful content.</p>
</section><!-- #block-3 -->
</div><!-- .clearfix -->
</div><!-- #wrapper-1 -->
</div><!-- #whitewrap -->
</body>
我需要的是每个SECTION拥有自己的WRAPPER div并在每个包装器周围添加一个CONTAINER div。 WRAPPERS和CONTAINERS的ID#需要自动增加,因为SECTIONS是动态添加的。
这就是我想象的。
<body>
<div id="whitewrap">
<div id="container-1">
<div id="wrapper-1" class="wrapper">
<div class="clearfix">
<section id="block-1">
<h1>Title</h1>
<p>Some wonderful content.</p>
</section><!-- #block-1 -->
</div><!-- .clearfix -->
</div><!-- #wrapper-1 -->
</div><!--#container-1 -->
<div id="container-2">
<div id="wrapper-2" class="wrapper">
<div class="clearfix">
<section id="block-2">
<h1>Title</h1>
<p>Some wonderful content.</p>
</section><!-- #block-2 -->
</div><!-- .clearfix -->
</div><!-- #wrapper-2 -->
</div><!--#container-2 -->
<div id="container-3">
<div id="wrapper-3" class="wrapper">
<div class="clearfix">
<section id="block-3">
<h1>Title</h1>
<p>Some wonderful content.</p>
</section><!-- #block-3 -->
</div><!-- .clearfix -->
</div><!-- #wrapper-3 -->
</div><!--#container-3 -->
</div><!-- #whitewrap -->
</body>
谢谢你们!
答案 0 :(得分:4)
使用jQuery的.wrap()
函数和递增计数器。将一个函数传递给.wrap()
,它会构建一个HTML代码段以围绕每个<section>
,根据需要使用计数器并递增它:
var counter = 1;
$('section').wrap(function() {
// Make a string of the HTML which should wrap around each <section>
var wrapper = '<div id="container-' + counter + '"><div id="wrapper-' + counter + '" class="wrapper"></div></div>';
// Increment the counter
counter++;
// Return the string and it will be applied around each <section>
return wrapper;
});
注意:你已经有了<div id="wrapper-1" />
整个事情。如果应该删除(如果wrapper-1
周围有另一个<section>
应该删除),请先使用.unwrap()
:
$("div.clearfix").unwrap();
// Then run the rest of the code...
答案 1 :(得分:1)
wrap
/ unwrap
就是您在这里寻找的内容。具体来说,为您提供索引参数的重载将有所帮助:
$("#block-1").unwrap().unwrap();
$("section").wrap(function(i) {
var num = i + 1;
return "<div id='container-" + num + "'>" +
"<div id='wrapper-" + num + "' class='wrapper'>" +
"<div class='clearfix'></div></div></div>";
});
答案 2 :(得分:0)