我刚开始学习 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>
谢谢大家!
最佳答案
使用 jQuery 的 .wrap()
具有递增计数器的功能。将函数传递给 .wrap()
它构建了一个 HTML 片段来包围每个 <section>
,根据需要在 ids 中使用计数器并递增它:
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...
关于javascript - 在 jQuery 中用递增的 id 包裹嵌套的 <div> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11697029/