4

我有以下 HTML 为一长串项目提供 ABC 链接,这些项目按字母表的字母分为页面。我无法更改 HTML。

<p>
    <a href="A.html">A</a>

    <!-- all the items on this page start with this letter 
         It is not contained in any special div, just floats among the links -->
    B

    <a href="c.html">C</a>        
    <a href="d.html">D</a>        
    <a href="e.html">E</a>        
    <a href="f.html">F</a>        
    <a href="g.html">G</a>

    <!-- and so on through z -->
</p>

我需要在每个字母之间放置一个分隔符(以下 HTML):

<span class="separator">|</span>

但是,如果我在每个链接之前或之后放置一个分隔符,那么纯字母本身和它周围的一个链接之间将没有分隔符。

如何在不更改 HTML 的情况下在每个链接之间放置分隔符,记住任何字母都可以是没有包含<a>或任何其他标记的纯文本,除了外部<p>

编辑以显示所需的结果(多种可能性中的两种)。粗体字母不是链接;所有其他字母是:

一个| 乙| C | D | E | F ...

一个 | 乙| C | D | E | F ...

4

2 回答 2

2

试试这个:

var p = // some method of getting the correct <p> tag
var c = p.childNodes, i, isfirst = true, s;
for(i=0;i<c.length;i++) { // skip the first child node
  if( c[i].tagName || c[i].nodeValue.match(/[a-z]/)) {
    // if node is a tag or a non-empty text node
    if( isfirst) isfirst = false; // skip first node
    else {
      s = p.insertBefore(document.createElement('span'),c[i]);
      s.className = "separator";
      s.appendChild(document.createTextNode("|"));
      i++; // IMPORTANT! Adding a node requires us to manually iterate forward one step!
    }
  }
}
于 2012-12-18T21:42:39.840 回答
2
var separator = "<span class='separator'>|</span>";

$("p").contents().each(function(){
    var $this = $(this);

    if($.trim($this.text()).length>0){
        if(this.nodeType == 3){
            // text node, possibly multiple characters that need separation
            var characters = this.nodeValue.replace(/\s/g, "").split("");
            var output = "";

            for(var i=0; i<characters.length; i++){
                output += " " + characters[i] + separator;
            }                    

            $(this).replaceWith(output + " ");                
        } else {
            $this.after(separator);
        }
    }
});

$(".separator:last").remove();

http://jsfiddle.net/kJ3yW/1/

于 2012-12-18T21:45:35.083 回答