用jQuery添加2个元素的换行(How to wrap in 2 elements with jQuery?)

编程入门 行业动态 更新时间:2024-10-19 08:44:24
用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

本文发布于:2023-08-07 01:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:换行   元素   jQuery   wrap   elements

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!