我试图将每个.test1和.test2类包装成一个div标签,但它包装整个div类。请建议。
HTML
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
的例外:
<div class="container">
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
</div>
<div class="container">
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
</div>
<div class="container">
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
</div>
Jquery:
$(".test1, .test2").wrapAll("<div class="container"></div>");
答案 0 :(得分:1)
"<div class="container"></div>"
)中的引号导致错误。This Fiddle根据上述假设显示了一种使其有效的方法:
// no-conflict safe shorthand document ready
jQuery(function($) {
$(".test1").each(function() {
$(this).next(".test2").addBack().wrapAll('<div class="container"></div>');
});
});
答案 1 :(得分:1)
你可以这样,使用CSS adjacent sibling combinator (+)进行快速选择:
$('.test1 + .test2').each(function() {
$(this).prev().addBack().wrapAll('<div class="container" />');
});
&#13;
.container {
border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
<div class="test1">This is demo paragraph1.</div>
<div class="test2">This is demo paragraph2.</div>
&#13;
同样在JSFiddle。
请注意,对于旧版本的jQuery,应使用addBack()
而不是andSelf()
方法。