用JQuery包装元素

时间:2010-01-12 20:33:03

标签: javascript jquery html

我的页面上有一个元素及其内容:

<div style="padding-bottom:9px; font-size:13px;line-height:25px;">          
  Fine quality, full grain pebble leather 
  <br>
  <div style="line-height: normal; margin-bottom: 6px; ">
     Sophisticated black with detailed accent lining
  </div>
  Tailored satin ribbon release pull-strap
  <br>
  Slim back pocket for an ID card or money
  <br>
  Ultra slim design
  <br>
  Shock-absorbent construction
  <br>
  Additional screen padding
  <br>
  Light and rigid protective layer
  <br>
  Soft velvet lining with light protective layer
  <br>
  <div style="line-height: normal; margin-bottom: 6px; ">
     Thinner and more streamlined than the Eléga Pouch
  </div>
  Sena high-quality handmade craftsmanship<br>      
</div>

我想要的是使用jQuery 将上面的内容转换为下面的内容(我尝试了不同的方法,但毕竟我有点丢失了)

<div style="padding-bottom:9px; font-size:13px;line-height:25px;">            
  <div style="line-height: normal; margin-bottom: 6px;">
      Fine quality, full grain pebble leather
  </div>
  <br/>
  <div style="line-height: normal; margin-bottom: 6px; ">
     Sophisticated black with detailed accent lining
  </div>
  <br/>
  <div style="line-height: normal; margin-bottom: 6px; ">
     Tailored satin ribbon release pull-strap
  </div>
  <br/>
  <div style="line-height: normal; margin-bottom: 6px; ">
     Slim back pocket for an ID card or money
  </div>
  <br/>
  <div style="line-height: normal; margin-bottom: 6px; ">
     Tailored satin ribbon release pull-strap
  </div>
  <br/>
   ...
   ...
   ...      
</div>

你能帮我一点吗。

感谢。

2 个答案:

答案 0 :(得分:1)

叫我老式,但转换那样的标记(特别是像<br><br/>)是应该在原始文件中完成的事情,而不是在jQuery被发送和呈现之后浏览器。

我认为在没有修改原始代码的情况下执行此操作会非常困难,因为您没有跨度或任何要查询的内容。

答案 1 :(得分:0)

以下是我正在寻找的解决方案:

jQuery("div").filter(lineHeight).contents(nonElementNodes).wrap("<div style='margin-bottom:9px;line-height:normal;margin-top:4px'>");

jQuery("div").filter(lineHeight).find("br").remove();

function lineHeight() {
  return this.style.lineHeight == "25px";
}

function nonElementNodes() {
  return this.nodeType !== 1 || this.tagName !== 'BR';
}

Source