用jquery或javascript添加一行换行符< br />在< div>的x个字符之后, [英] Jquery or javascript to add one line break <br /> after x amount of characters in a <div>

查看:108
本文介绍了用jquery或javascript添加一行换行符< br />在< div>的x个字符之后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在< div>的前4或5个字符之后插入< br /> ; 。例如:
< div id =wine-name> 2008 Cabernet Sauvignon

显示如下:


2008

赤霞珠



不确定哪一个更容易使用javascript或jQuery。



任何想法?

解决方案

如果你确定你总是希望在第四个字符后插入break,你可以这样做:

  var html = $ ( #酒名)HTML(); 
html = html.substring(0,4)+< br> + html.substring(4);
$(#wine-name)。html(html);

您可以在行动中看到它

如果你想让它在第一个单词之后分隔(用空格分隔),你可以这样做:

  var html = $(#wine-name)。html()。split(); 
html = html [0] +< br> + html.slice(1).join();
$(#wine-name)。html(html);

您可以在行动中看到 here



编辑您的评论:

<$ p $($。$)$。$(。); $ b $(。wine-name)。 b html = html [0] +< br>+ html.slice(1).join();
$(this).html(html);
});

查看在这里


I am looking for a way to insert a <br /> after only the first 4 or 5 characters in a <div>.

Example: <div id="wine-name">2008 Cabernet Sauvignon</div>

To display like:

2008
Cabernet Sauvignon

Not sure which would be easier javascript or jQuery. The site is already using jQuery.

Any ideas?

解决方案

If you are certain that you always want to insert the break after the fourth character, you can do this:

var html = $("#wine-name").html();
html = html.substring(0, 4) + "<br>" + html.substring(4);
$("#wine-name").html(html);

You can see it in action here.

If you want it to instead break after the first word (delimited by spaces), you can do this instead:

var html = $("#wine-name").html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$("#wine-name").html(html);

You can see this in action here.

EDITed for your comment:

$(".wine-name").each(function() {
    var html = $(this).html().split(" ");
    html = html[0] + "<br>" + html.slice(1).join(" ");
    $(this).html(html);
});

See it here.

这篇关于用jquery或javascript添加一行换行符&lt; br /&gt;在&lt; div&gt;的x个字符之后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆