PS:更新小提琴
这是一个fiddle,用于包含元素中的文本
这里有fiddle尝试使用逗号分隔文本作为分隔符,并将<span class="new"/>
中的每个单词换行。有人请告诉我为什么它会在foreach循环中给我Uncaught TypeError: undefined is not a function
吗?
我希望输出为
<td>
<span class='new'>Text</span>
<span class='new'>that</span>
<span class='new'>needs</span>
<span class='new'>to</span>
<span class='new'>be</span>
<span class='new'>wrapped.</span>
<span class="count">not this</span>
<button>Wrap</button>
</td>
代码:
$('button').click(function(){
var wrap_it = $(this).closest('td').contents().eq(0).text();
wrap_it = wrap_it.split(',');
console.log(wrap_it);
$.each(wrap_it,function(i,k){
k.wrap('<span class="new"/>');
})
});
HTML:
<table>
<tbody>
<tr>
<td>1</td>
<td>Text,that, needs, to, be, wrapped.<span class="count">not this</span><button>Wrap</button>
</td>
</tr>
<tr>
<td>2</td>
<td>Text, that, needs, to, be, wrapped.<span class="count">not this</span><button>Wrap</button></td>
</tr>
</tbody>
</table>
答案 0 :(得分:2)
我试了一下:
$('button').click(function(){
var text = $(this).closest('td').contents().eq(0).text().split(",");
var keep = $(this).closest('td').find(".count");
var button = $(this).closest('td').find('button');
for( var i = 0, len = text.length; i < len; i++ ) {
text[i] = '<span class="new">' + text[i] + '</span>';
}
$(this).closest('td').html(text.join(' ')).append(keep).append(button);
});
请告诉我,如果它适合你。
答案 1 :(得分:2)
也试一试
$('button').click(function () {
var text = $(this).closest('td').contents().eq(0).text().split(','),
len = text.length,
result = [];
for( var i = 0; i < len; i++ ) {
result[i] = '<span class="new">' + text[i] + '</span>';
}
var keep = $(this).closest('td').find(".count"),
button = $(this).closest('td').find('button');
$(this).closest('td').html(result.join(' ')).append(keep).append(button);
});
小提琴: Wrap splitted text