本文介绍了选择具有两个类的元素并将其包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HTML
<div>
<span class="openParen bm0">(</span>
<span class="closeParen bm0">)</span>
<span class="openParen bm3">(</span>
<span class="openCurly bm1">{</span>
<span class="openParen bm2">(</span>
<span class="closeParen bm2">)</span>
<span class="closeParen bm3">)</span>
<span class="closeCurly bm1">}</span>
</div>
更新我希望使用bm类名将其成对包装在<span class="new"></span>
中,而我只想将使用Paren作为类名的包装起来
UPDATEI wanted this to be wrapped in <span class="new"></span>
by pairs using the bm classname, and i only wanted to wrapped those with Paren on their class name
无法正确包装
<div>
<div>if<span class="openParen bm1">(</span>b<3 && b>0<span class="closeParen bm1">)</span>{</div>
</div>
推荐答案
您可以使用 .wrapAll()并使用bm0
类选择元素
You can use .wrapAll() and use the bm0
class to select the elements
var ops = /(==|<=|>=|!=|>|<)/,
prev = /(if|else\s+if|while|for)/;
$('.openParen').each(function () {
var bm = this.className.match(/\b(bm\d+)\b/)[1],
$this = $(this),
$close = $('.closeParen.' + bm);
var $set = $(this),
next = this.nextSibling;
while (next) {
$set = $set.add(next);
if ($close.is(next)) {
break;
}
next = next.nextSibling;
}
if (ops.test($set.text())) {
var prevEl = this.previousSibling;
var $span = $set.wrapAll('<span class="new"></span>').parent();
if (prevEl && prevEl.nodeType == 3 && prev.test($(prevEl).text())) {
$span.prepend(prevEl)
}
}
})
演示:小提琴
这篇关于选择具有两个类的元素并将其包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!