用jQuery添加2个元素的换行(How to wrap in 2 elements with jQuery?)
Ori:
<h2>TEXTz</h2> <p>ARTICLE</p> <h2>TEXTx</h2> <p>ARTICLE</p>对此
<div class="highlight"> <h2>TEXTz</h2> <p>ARTICLE</p> </div> <h2>TEXTx</h2> <p>ARTICLE</p>但我必须使用:包含查找h2文本并在h2之前和之后添加换行
任何想法 .... ?
我的失败代码:
$.extend($.expr[':'],{containsExact: function(a,i,m){return $.trim(a.innerHTML.toLowerCase()) === m[3].toLowerCase();}}); var byItem = "TEXTz" var ItemTitle = $("h2:containsExact(" + byItem +")").text(); var ItemDes = $("h2:containsExact(" + byItem +")").next("p").text(); $("h2:containsExact(" + byItem +")").html('<section class="highlightitem"><h2>' + ItemTitle + '</h2><p>' + ItemDes + '</p></div>');http://jsfiddle.net/NDUzW/
I want to make the following code:
<h2>TEXTz</h2> <p>ARTICLE</p> <h2>TEXTx</h2> <p>ARTICLE</p>Look like this:
<div class="highlight"> <h2>TEXTz</h2> <p>ARTICLE</p> </div> <h2>TEXTx</h2> <p>ARTICLE</p>But I have to use: contains for find h2 text and add wrap before h2 and after p.
My failed code:
$.extend($.expr[':'],{containsExact: function(a,i,m){return $.trim(a.innerHTML.toLowerCase()) === m[3].toLowerCase();}}); var byItem = "TEXTz" var ItemTitle = $("h2:containsExact(" + byItem +")").text(); var ItemDes = $("h2:containsExact(" + byItem +")").next("p").text(); $("h2:containsExact(" + byItem +")").html('<section class="highlightitem"><h2>' + ItemTitle + '</h2><p>' + ItemDes + '</p></div>');http://jsfiddle.net/NDUzW/
最满意答案
方法.add()允许向jquery对象添加元素。
然后你可以使用.wrapAll()来擦除jQuery中的一组元素。
var $h2 = $("h2:containsExact(" + byItem +")"); if ($h2.length) { $h2.add( $h2.next('p') ) .wrapAll( $('<div>').addClass('highlight') ); }关于jsfiddle的工作示例
The method .add() allows adding elements to a jquery object.
Then you can use .wrapAll() to wrape a set of elements in jQuery.
var $h2 = $("h2:containsExact(" + byItem +")"); if ($h2.length) { $h2.add( $h2.next('p') ) .wrapAll( $('<div>').addClass('highlight') ); }Working example on jsfiddle
更多推荐
p>,<p>ARTICLE<,电脑培训,计算机培训,IT培训"/> <meta name="de
发布评论