0

仅CONTENTEDITABLE DIV示例字符串

int main(){

 if((x<3 && x!=5) || x>10)
   //execute statement;

 while((y<10) && (y>1))
   //execute statement;

}

DIV 的现有 HTML

<div id="board_code">
 <div>int main<span class="openParen bm1">(</span><span class="closeParen bm1">)</span></div>
 <div></div>
 <div>if<span class="openParen bm2">(</span><span class="openParen bm3">(</span>x<3 && x!=5<span class="closeParen bm3">)</span> || x>10<span class="closeParen bm2">)</span></div>
 <div>//execute statement;</div>
 <div>while<span class="openParen bm4">(</span><span class="openParen bm5">(</span>y<10<span class="closeParen bm5">)</span> && <span class="openParen bm6">(</span>y>1<span class="closeParen bm6">)</span><span class="closeParen bm4">)</span></div>
 <div>//execute statement;</div>
 <div>}</div>
</div>

目标 HTML

<div id="board_code">
 <div>int main<span class="parenWrap"><span class="openParen bm1">(</span><span class="closeParen bm1">)</span></span></div>
 <div></div>
 <div>if<span class="parenWrap"><span class="openParen bm2">(</span><span class="parenWrap"><span class="openParen bm3">(</span>x<3 && x!=5<span class="closeParen bm3">)</span></span> || x>10<span class="closeParen bm2">)</span></span></div>
 <div>//execute statement;</div>
 <div>while<span class="parenWrap"><span class="openParen bm4">(</span><span class="parenWrap"><span class="openParen bm5">(</span>y<10<span class="closeParen bm5">)</span></span> && <span class="parenWrap"><span class="openParen bm6">(</span>y>1<span class="closeParen bm6">)</span></span><span class="closeParen bm4">)</span></span></div>
 <div>//execute statement;</div>
 <div>}</div>
</div>

我已经()通过一对等来匹配了bm1, bm2。现在,我需要openParen bm(n)closeParen bm(n)span class = parenWrap

我怎样才能做到这一点?

简化

<span class="parenWrap">((x<3 && x!=5) || x>10)</span>
<span class="parenWrap">(x<3 && x!=5)</span>
<span class="parenWrap">((y<10) && (y>1))</span>
<span class="parenWrap">(y<10)</span>
<span class="parenWrap">(y>1)</span>

为了更容易理解,他们会变成这样,保留他们已经拥有的span标签

基于@pdoherty926 答案的更新

逻辑类似于

//if i have 3 pairs of bm's
    for(var xx=1; xx<4; xx++){
         $('.openParen bm'+xx).nextUntil('.closeParen bm'+xx).andSelf().wrapAll('<span class="parenWrap"></span>');
    }//for

但这不起作用。

4

1 回答 1

2
<div>   
    one
    <span class="openParen bm1">(</span>
    <span>sometext here</span>
    <span class="closeParen bm1">)</span>
</div>


$('.openParen').each(function () {
    $(this).nextUntil('.closeParen').andSelf().wrapAll('<span class="parenWrap"></span>');
});

小提琴

于 2013-09-03T04:11:55.320 回答