使用jQuery在文本的特定部分之前添加<br/>

时间:2011-06-16 22:56:03

标签: jquery html

我有两个这样的段落:

<p>text bla bla bla owner of the idea : John Smith</p>
<p>text bla bla bla bla bla bla owner of the idea : James Marino</p>

有没有什么方法可以使用jQuery在“想法的所有者”之前添加一个新行直到句子结尾?

提前致谢

6 个答案:

答案 0 :(得分:6)

如果这是jquery脚本的副本,请尝试使用\n作为新行。这项工作在javascripts。

jQuery WORKING示例:

 <p id="s">text bla bla bla owner of the idea : John Smith</p>
<p>text bla bla bla bla bla bla owner of the idea : James Marino</p>

<script type="text/javascript">
    $(document).ready(function() {
        $("p").each(function() {
            var getContent=$(this).text();
            var newString=getContent.replace('owner of the idea','<br />owner of the idea');
            $(this).html(newString);
        });
    });
</script>

答案 1 :(得分:5)

如果模式一致,您可以根据:字符进行替换。

 $('p').each(function(){ 
          this.html(this.html().replace(":",":<br />"));
 }); 

<击>

<强>更新

根据评论,看起来我误解了这个问题。但是,您仍然可以使用相同的策略,

  var p = $('p:first');
  p.html(p.html().replace("owner of the idea", "<br />owner of the idea"));

答案 2 :(得分:1)

$('<br />').insertBefore(selector for your paragraph);

我不知道您的周围标记是什么样的,因此不清楚段落的最佳选择器是什么。

答案 3 :(得分:1)

$('p').each(function() {
    $(this).html($(this).text().replace(/\bowner of the idea/i,'<br/>$&'));
});

答案 4 :(得分:0)

在休息时间上课,然后随意显示和隐藏,如下:

HTML:

<br class="break" style="display:none;"/>

jquery的:

$('.break').show();
$('.break').hide();

答案 5 :(得分:-1)

您只需使用此JavaScript将<br />添加到段落中:

$("p").prepend("<br />");

更新我明白你的意思了......试试这段代码:

var old=$("p").html();
$("p").html(old.replace(/owner/gi,"<br />owner");

广告@米