在页面上的特定单词后插入换行符

时间:2014-06-16 21:15:42

标签: jquery

我正在尝试编辑此代码,

我的页面上有一个横向排列的人员列表,但我希望在特定人员的姓名后插入一个换行符。

我的换行符有一个div。它是<div class="newline">

$(window).load( function(){
  $("#peoplelist p").text("Roger John");
  var html = $(this).html().split(" ");
  html = html[0] + "<br>" + html.slice(1).join(" ");
  $(this).html(html);
});    

但这不起作用,有人可以帮我这个吗?

3 个答案:

答案 0 :(得分:1)

如果您知道人名,您可以这样做,不需要阵列和加入,不需要:

小提琴: http://jsfiddle.net/9CdtL/


HTML

<div id="peoplelist"><p>Chris Jean, Vic Sen, Roger John, Dan Vany</p></div>

<强> JS

$(window).on('load',function(){
    //here I set the name-var to the name I want the linebreak after
    //Now this is quite static, but this could of course also be done using data from a database or something.
    var name = 'Roger';

    //Here I insert the linebreak after the name using 'replace()'
    $('#peoplelist p').html($('#peoplelist p').html().replace(name+' ',name+'<br>'));
});

主线是:[string].replace(name+' ', name+'<br>');


修改

我改变了整个答案。对不起,我应该更清楚的是,之前的回答只显示了您在控制台中的结果,页面上没有任何地方。它现在。

BTW ,您对$(this)的使用是错误的,这是您的代码无法正常工作的原因之一。您只能在元素的动作函数中使用$(this) 您只是在$("#peoplelist p").text("Roger John");行的下一行使用它 从技术上讲,在你的情况下$(this)引用了window-object,因为它在window-load-function中。但是,无论如何,这都不会起作用,因为窗口不是页面上可以容纳内容的元素。

答案 1 :(得分:0)

由于$(this)指的是窗口,

无法正常工作。

您应该尝试这个并直接引用该对象。

$(window).load(function(){
    var $listp = $("#peoplelist p")

    $listp.text("Roger John");

    var html = $listp.html().split(" ");
    html = html[0] + "<br>" + html.slice(1).join(" ");
    $listp.html(html);
});

答案 2 :(得分:0)

我不确定这是否是最优雅的解决方案,但是对我来说行之有效的是清空文本,然后通过'.wrapInner()'函数(可以包含HTML)替换它:

-templates
   -registration
       password_reset_email.html

http://jsfiddle.net/h1d78sm9/1/