简体   繁体   English

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

[英]How to combine tags as long as they have the same class

The Html that I'm getting ideally looks like this: 理想的Html看起来像这样:

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

Next my aim is to change the span tag into an anchor tag. 接下来我的目标是将span标记更改为锚标记。 With the ideal Html, I have done it this way: 有了理想的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);

Now, the problem comes when I'm actually getting this sort of Html (please note, I can't change the Html input): 现在,当我真正得到这种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>

The question is: 问题是:

How could I get it to work with such a broken set of spans? 我怎么能让它与这样一组破碎的跨度一起工作?

I'm thinking the following: 我在想以下几点:

  • Find an expected link span 找到预期的链接范围
  • Check whether the immediate next element is also a span with the same class 检查紧邻的下一个元素是否也是具有相同类的跨度
  • and then check whether the immediate next element is also..., 然后检查下一个元素是否也是......,
  • and then check... 然后检查......
  • if none is found, combine the innerHtml of each span into a single anchor tag 如果未找到,则将每个范围的innerHtml组合成单个锚标记

How could I achieve such a loop? 我怎么能实现这样的循环?

Thanks. 谢谢。

There is the + selector which selects consecutive elements: http://jsfiddle.net/NWWYC/1/ . +选择器选择连续的元素: 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM