2010-06-04 33 views
5

我已经花了两天时间,所以如果有简单的答案,我会感到灰心。我试图在div中的每个字母周围放置一个span标签,同时保留其余标签不变。使用jQuery:如何将每个字母包装在标签中?

<div id="div"> 
    <p> 
     Of course some of the <strong>text is in other tags</strong> and <strong>some 
     is in <em>nested tags</em>, etc.</strong> 
    </p> 
</div> 

我变得非常接近,但最终总是让我失望。

+0

符合儿童的标签也应该得到周围标签的字母? – 2010-06-04 20:15:38

+5

你为什么想这样做? – aviraldg 2010-06-04 20:16:08

+0

这是不知道嵌套标记,但可能会给一些groudnwork:http://stackoverflow.com/questions/1966476/javascript-process-each-letter-of-text – 2010-06-04 20:16:35

回答

2

我明白了!这可能不是最佳的解决方案,但它的工作原理!还要注意,由于额外的标签,空白可能会混乱。这也包装标签,但也很容易解决。

function wrap(target) { 
    var newtarget = $("<div></div>"); 
    nodes = target.contents().clone(); // the clone is critical! 
    nodes.each(function() { 
     if (this.nodeType == 3) { // text 
      var newhtml = ""; 
      var text = this.wholeText; // maybe "textContent" is better? 
      for (var i=0; i < text.length; i++) { 
       if (text[i] == ' ') newhtml += " "; 
       else newhtml += "<span>" + text[i] + "</span>"; 
      } 
      newtarget.append($(newhtml)); 
     } 
     else { // recursion FTW! 
      $(this).html(wrap($(this))); 
      newtarget.append($(this)); 
     } 
    }); 
    return newtarget.html(); 
} 

用法:

$("#div").html(wrap($("#div"))); 
+0

这似乎不适用于我 - 我可以看到它正确地在调试器中建立newhtml字符串,但是'$(this).html(newhtml)'不会导致输出的任何更改.. – Ryley 2010-06-04 21:04:25

+0

我修好了!也许更多的人可以设法优化? – Tesserex 2010-06-04 21:23:10

+0

我也只是在保存的jQuery api页面副本上进行了测试。它花了一秒钟,但它的工作,页面外观没有改变,一切都完好无损。似乎工作。 – Tesserex 2010-06-04 21:30:02

1
function init(target) { 
var newtarget = $('<div></div>'); 
nodes = target.contents().clone(); // the clone is critical! 
nodes.each(function(i,v) { 
    if (v.nodeType == 3) { // text 
     if($.trim($(this).text()).length>0){ 
      var letters=$(this).text().split(''); 
      for (var j = 0; j < letters.length; j++) { 
       newtarget.append('<span class="letter">'+letters[j]+'</span>') 
      } 
     } 
    } 
    else { // recursion FTW! 
     newtarget.append($(this)); 
     $(this).html(init($(this))); 
    } 
}); 
return newtarget.html(); 
} 

这工作得相当好。然而,也就是(无论如何7),将所有的空间去掉。另外,我应该从函数结尾处的dom中移除newtarget吗?克隆怎么样?应该删除?

相关问题