2012-08-17 18 views
1

是我得到理想看起來像這樣的HTML結合:如何標記,只要它們具有相同的類

<span class="RapidLink1-H">See the more detailed areas of what not</span> 

下一步我的目標是span標籤變成一個錨標記。有了理想的Html,我已經這樣做了:

  // Walk through each link tag on this page and replace the content with an actual link 
      thisLink.each(function() { 

       linkRefTarget = ''; 

       // Get only the identifier number of the link 
       linkId = ($(this).attr('class')).replace(/[A-Za-z$-]/g, ''); 

       // Match this link with the list of link references 
       if (thisLinkRef) { 
        for (var key in thisLinkRef) { 
         if (key == 'link' + linkId) linkRefTarget = thisLinkRef[key]; 
        } 
       } 

       output = ''; 
       output+= '<a href="#' + linkRefTarget + '" id="link' + linkId + '" class="rapidLink">'; 
       output+= $(this).html(); 
       output+= '</a>'; 

      }).replaceWith(output); 

現在的問題是當我真的開始這類的HTML(請注意,我不能改變HTML輸入):

<span class="RapidLink1-H">See the</span><span class="RapidLink1-H">more detailed areas of</span><span class="RapidLink1-H">what not</span></span> 

的問題是:

我怎麼能得到它與這樣一個破碎的集跨越的工作嗎?

我想以下幾點:

  • 查找預期的連接架
  • 檢查緊跟其後的元素是否也與同級別的跨度
  • ,然後檢查是否緊跟其後元素也是...,
  • 然後檢查...
  • 如果沒有找到,則將每個跨度的innerHtml組合爲單個錨標記

我怎麼能達到這樣一個循環?

謝謝。

+0

我知道DOM操作使用正則表達式都沒有做,但我幾乎建議更換所有'的'在你的HTML。這聽起來比您提出的想法容易得多。 – Hidde 2012-08-17 10:44:12

回答

3

+選擇器選擇連續元素:http://jsfiddle.net/NWWYC/1/

$(".RapidLink1-H + .RapidLink1-H").each(function() { 
    // move contents to previous span, remove this span afterwards 
    $(this).prev(".RapidLink1-H").append(
     $(this).contents() 
    ).end().remove(); 
}); 
+0

'$(this).contents()'和'$(this).html()' – 2012-08-17 11:05:45

+0

@Dariush Jafari:'.html()'返回一個表示節點的字符串。 '.contents()'返回節點本身。一個優點是當您移動節點時事件仍然受到約束。如果您在過程中將字符串轉換爲字符串並從字符串轉換,則此類信息將丟失 – pimvdb 2012-08-17 11:26:21

相關問題