1

我想将 html DOM 节点内的所有元素拆分为带有 id 的 span,例如:

假设我有元素:

<div>
<h1>Header</h1>
<h2>header2</h2>
<p class="test">this is test p</p>
</div>

结果应该是:

<div>
<h1><span id="1">Header</span></h1>
<h2><span id="2">header2</span></h2>
<p class="test"><span id="3">this</span><span id="4">is</span><span id="5">test</span> <span id="6">p</span></p>
</div>

谢谢你的帮助

如果有嵌套图像,它也应该工作,例如:

<div>
<h1>Header</h1>
<h2>header2</h2>
<p class="test"><img alt="test alt" />this is test p</p>
</div>

结果:

<div>
<h1><span id="1">Header</span></h1>
<h2><span id="2">header2</span></h2>
<p class="test"><img alt="test alt" /><span id="3">this</span><span id="4">is</span><span id="5">test</span> <span id="6">p</span></p>
</div>
4

2 回答 2

7

jsBin 演示

像这样包装每个单词应该会有所帮助:

var c = 0;                                // create a counter
$('div > *').each(function(){
    var text = $(this).html().split(' '), // split your text strings
        len = text.length,                // get lenght of splitted parts
        result = [];                      // create array
    for( i=0; i<len; i++ ) {              // looping 'len' times....
        result[i] = '<span id="'+( ++c )+'">' + text[i] + '</span>';  // populate array
    }
    $(this).html(result.join(' '));       // apply edits
});   
于 2012-09-25T21:09:02.650 回答
0
var str = $('.test').text();
var result = "";
str = str.split(" ");
$.each(str,function() {
   result += '<span>' + this + '</span>';
});
$('.test').html($(result));
于 2012-09-25T21:11:59.047 回答