我想在 html 超过 50 个字符后使用 jQuery 向我的 html 添加一个“<br />
”标签。
我的 HTML:
<table>
<tr>
<td class="ccol1">This is the HTML if its characters exceed 50 characters it should go to next line</td>
</tr>
</table>
我尝试使用 google 的结果来执行此操作,但它似乎不起作用。
$( '.ccol1' ).each( function () {
var str = $('td' + '.ccol1');
var htmlfoo = str.match(/.{1,50}/g).join("<br/>");
$( this ).html( str );
});
此外,我必须单独使用 jQuery 来完成此操作,因此请不要建议使用 CSS 自动换行。
谢谢
最佳答案
这是一个基于您现有代码的 JSFiddle 链接。
代码片段如下
$('.ccol1').each(function () {
var str = $(this).html();
var htmlfoo = str.match(/.{1,50}/g).join("<br/>");
$(this).html(htmlfoo);
});
注意 var str = $(this).html();
它指的是 each
中的元素以防止弄乱其他<td>
具有相同类的元素。
关于jQuery 在 50 个字符后的文本中添加一个 <br>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24948126/