如果标签具有相同的类,如何组合标签

时间:2012-08-17 10:40:04

标签: javascript jquery html

我正在理想的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组合成单个锚标记

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

感谢。

1 个答案:

答案 0 :(得分: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();
});