分割文本并在jQuery中的元素中包装每个单词 [英] Splitting text and wrapping each of the words in elements in jQuery
本文介绍了分割文本并在jQuery中的元素中包装每个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PS:更新小提琴
Here's a fiddle that wraps text in elements
这是小提琴
Here's a fiddle trying to split text using commas as delimiters and wrap each of the words in <span class="new"/>
. Would anyone please tell me why it gives me Uncaught TypeError: undefined is not a function
in the foreach loop?
我希望输出为
I want the output to be
<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>
代码:
Code:
$('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:
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>
推荐答案
我做了一个尝试:
$('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);
});
请告诉我,如果它适合您。
Tell me please if it suits you.
这篇关于分割文本并在jQuery中的元素中包装每个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文