jQuery 在 50 个字符后的文本中添加一个 <br>

标签 jquery html css

我想在 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 链接。

Link

代码片段如下

$('.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/

相关文章:

javascript - Angularjs 和 $ 选择器

javascript - 为下拉框提供验证

javascript - 是在 css 中使用 javascript

java - 有没有办法为 JavaFX 类提供一个新样式的类,然后正常访问该类中的所有其他对象?

javascript - 在服务器上发布后,CSS 或 Javascript 文件不起作用

javascript - 收到 AJAX 结果后加载器不会消失

javascript - Jquery 并将事件绑定(bind)到 iframe

css - 使用 margin-auto 垂直对齐任何 div 中的任何内联元素

html - CSS 文本从错误的地方开始

javascript - 嵌入式 JavaScript 无法在 IE 10 或 11 中运行(在 Chrome 和 Firefox 中运行良好)