2012-08-17 40 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