JQuery .text()Multi-Line

时间:2017-06-05 13:12:00

标签: jquery

有没有办法可以将这段令人讨厌的长篇文章变成段落?

在:

$('.ContText-1').text('For a business to thrive, it needs a team of people who are dedicated to its success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of that team for each of their clients.');

之后:

$('.ContText-1').text('
             For a business to thrive, it needs a team of people who are dedicated to its 
        success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of 
        that team for each of their clients.
');

如果我运行第一段,我会收到此错误:Uncaught SyntaxError: Invalid or unexpected token
它引用了(之后的单引号。

3 个答案:

答案 0 :(得分:1)

假设您试图破坏代码中的字符串而不是输出,您可以通过使用`分隔字符串来使用模板文字:

$('.ContText-1').text(`
  For a business to thrive, it needs a team of people who are dedicated to its 
  success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of 
  that team for each of their clients.
`);

请注意,在任何版本的IE中都完全不支持此功能,但在所有其他现代浏览器中均可使用 - 甚至是Edge。

或者,您可以单独附加每一行:

$('.ContText-1').text(
  'For a business to thrive, it needs a team of people who are dedicated to its ' + 
  'success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of ' + 
  'that team for each of their clients.'
);

答案 1 :(得分:0)

代替text()方法使用html()方法,并使用<br/>来破解该行

$('.ContText-1').html('<br/>For a business to thrive, it needs a team of people who are dedicated to its <br/>success. Paul Lister, Bryan Jeter, and Bryan Lloyd are committed to being a part of <br/> that team for each of their clients.');

答案 2 :(得分:0)

不要用'包围字符串',而是尝试使用`。

至少在JS的新版本中,这应该可以正常工作。

更新:

实际上,之前已经介绍过:Creating multiline strings in JavaScript