如何组合标签,只要它们具有相同的类

How to combine tags as long as they have the same class

本文关键字:何组合 组合 标签      更新时间:2023-09-26

理想情况下得到的 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 合并到单个锚标记中

我怎样才能实现这样的循环?

谢谢。

有一个选择连续元素的+选择器: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();
});