我刚开始学习jQuery,遇到了一个难住我的问题。我需要移动,添加和命名div而不影响内容。
我有一个固定宽度的包装器div,里面有部分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>我需要的是每个部分都有自己的包装器div,并在每个包装器周围添加一个容器div。包装器和容器的ID #需要自动增加,因为这些部分是动态添加的。
这就是我所想的。
<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>谢谢你们!
发布于 2012-07-28 08:21:30
发布于 2012-07-28 07:59:44
使用带有递增计数器的jQuery的.wrap()函数。将一个函数传递给.wrap(),该函数构建一个HTML代码片段来包围每个<section>,根据需要在it中使用计数器并递增它:
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" />。如果应该将其删除(如果<section>周围有另一个wrapper-1,则应该删除),请首先使用.unwrap():
$("div.clearfix").unwrap();
// Then run the rest of the code...https://stackoverflow.com/questions/11697029
复制相似问题