【问题标题】:How to wrap in 2 elements with jQuery?如何用 jQuery 包装 2 个元素?
【发布时间】:2012-01-13 10:34:11
【问题描述】:

我想做如下代码:

<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 之前和 p 之后添加换行。

我失败的代码:

$.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/

【问题讨论】:

    标签: javascript jquery find


    【解决方案1】:

    .add() 方法允许向 jquery 对象添加元素。

    然后你可以使用.wrapAll()在jQuery中包装一组元素。

    var $h2 = $("h2:containsExact(" + byItem +")");
    if ($h2.length) {
        $h2.add( $h2.next('p') )
           .wrapAll( $('<div>').addClass('highlight') );
    }
    

    jsfiddle 上的工作示例

    【讨论】:

      【解决方案2】:

      只需使用 jQuery 函数:

      var byItem = "TEXTz"
      
          $("h2")
              .filter(
                  function() {
                      if ($(this).html() == byItem) {
                          return true;
                      }
                      return false;
                 }
             )
             .next("p")
             .andSelf()
             .wrapAll($("<section>")
                  .addClass("highlightitem")
             );
      

      Example

      【讨论】:

        猜你喜欢
        • 2012-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        相关资源
        最近更新 更多