简体   繁体   English

在 javascript 代码中将字符串分成多行

[英]Breaking a string into multiple lines inside a javascript code

I am trying to format (beautify, tidy, clear up.. you name it) a snippet of HTML inside my javascript code or, in other words, spread it out on multiple lines rather than having it written on one line so it can be read easily.我正在尝试在我的 javascript 代码中格式化(美化、整理、清理 .. 你的名字)HTML 的片段,或者换句话说,将它分散在多行而不是写在一行上,这样它就可以轻松阅读。

Basically, it's a piece of html code that I am trying to append to the page by calling the jQuery's .append();基本上,这是一段 html 代码,我试图通过调用 jQuery 的.append();将 append 到页面。 method.方法。

And here's what I am trying to do:这就是我想要做的:

$('.videos').append('<li>
                    <span>' + count + '</span> - 
                    <a href="' + vList[i].player + '">
                        <span class="title">' + videoTitle + '</span>
                    </a>
                    </li>');

Appearantly, it won't work that way.显然,它不会那样工作。 I am getting Uncaught SyntaxError: Unexpected token >我收到Uncaught SyntaxError: Unexpected token >

When It is written as follows, everything works fine.当它写成如下时,一切正常。

$('.videos').append('<li><span>' + count + '</span> - <a href="' + vList[i].player + '"><span class="title">' + videoTitle + '</span></a></li>');

It's kind of weird that when I tried to do the exact thing here,有点奇怪,当我试图在这里做同样的事情时,

var albumURL = API + '/video.get?=owner_id=' + userID +
                     '&album_id=' + aList[i].album_id +
                     '&access_token=' + accessToken;

I had no problem at all.我一点问题都没有。

I know this issue is not that big of a deal but I am trying to get around with it just for the sake of simplicity.我知道这个问题没什么大不了的,但为了简单起见,我正试图解决这个问题。

Any suggestions?有什么建议么?

If you have a multiline string, you need to use the multiline string syntax .如果您有一个多行字符串,则需要使用多行字符串语法

However, it's better to store your HTML in templates and not code :) That makes them more readable, more reusable and more maintainable.但是,最好将 HTML 存储在模板中而不是代码中 :) 这使它们更具可读性、更可重用和更易于维护。

What about something like - in your HTML:怎么样 - 在你的 HTML 中:

<script type="text/template" id="videoTemplate">
    <li>
      <span>{{count}}</span>
      <a href="{{videoURL}}">
        <span class="title">{{videoTitle}}</span>
      </a>
    </li>
</script>

Then in JavaScript然后在 JavaScript 中

var template = $("#videoTemplate").html();
$(".videos").append(template.replace("{{count}}",count).
                             replace("{{videoURL}}",vList[i].player).
                             replace("{{videoTitle}}",videoTitle));

That way, you get a clearer separation of the template you're using and your code.这样,您可以更清晰地分离您正在使用的模板和您的代码。 You can change the HTML independently and reuse it in other parts of code more easily.您可以独立更改 HTML 并更轻松地在代码的其他部分重用它。

The code does not have to even be aware of template changes and a designer can change the design without knowing JavaScript.代码甚至不必知道模板更改,设计人员可以在不了解 JavaScript 的情况下更改设计。

Of course, if you find yourself doing this often you can use a templating engine and not having a .replace chain.当然,如果您发现自己经常这样做,您可以使用模板引擎而不是.replace链。

ES2015 also introduces template strings which are also kind of nice and serve the same purpose in principle: ES2015 还引入了模板字符串,它们也很好用,原则上具有相同的目的:

 const videoTemplate = `<li>
      <span>${count}</span>
      <a href="${vList[i].player}">
        <span class="title">${videoTitle}</span>
      </a>
    </li>`;

If you want to write a multiline string you should use the "\\":如果你想写一个多行字符串,你应该使用“\\”:

example:例子:

$('.videos').append('<li> \
                <span>' + count + '</span> - \
                <a href="' + vList[i].player + '"> \
                    <span class="title">' + videoTitle + '</span> \
                </a> \
                </li>');

New answer:新答案:

With ES6 you can actually use string concatenation that is line-break insensible:使用 ES6,您实际上可以使用不区分换行符的字符串连接:

var html = `
    <li>
        ${count}
    </li>
`;

and the line breaks will not be a problem.并且换行不会有问题。 Prior to ES6 I used mostly arrays and concat them.在 ES6 之前,我主要使用数组并将它们连接起来。 Its faster:它更快:

var html = [
    '<li>',
        count
    '</li>'
].join('');

Old answer:旧答案:

In javascript you cannot break lines without concatenating them with a + or using \\ .在 javascript 中,如果不使用+或使用\\将它们连接起来,就无法断行。 Try this:试试这个:

$('.videos').append('<li>' +
    '<span>' + count + '</span> - ' +
    '<a href="' + vList[i].player + '">' +
    '<span class="title">' + videoTitle + '</span>' +
    '</a>' +
    '</li>'); 

If you simply want to split rendered output onto new lines then append \\n where you want the newline to appear, like this...如果您只是想将渲染输出拆分为新行,则在您希望换行符出现的位置附加 \\n,就像这样...

$('.videos').append('<li>\n<span>' + count + '</span> -\n<a href="' + vList[i].player + '">\n<span class="title">' + videoTitle + '</span>\n</a>\n</li>\n');

And if you want your JS to look nice you could try this, which will also ensure that your rendered HTML is indented.如果你想让你的 JS 看起来不错,你可以试试这个,这也将确保你呈现的 HTML 是缩进的。

var item = '';

item += '<li>\n';
item += '    <span>' + count + '</span> -\n';
item += '    <a href="' + vList[i].player + '">\n';
item += '        <span class="title">' + videoTitle + '</span>\n';
item += '    </a>\n';
item += '</li>\n';

$('.videos').append(item);

you can try like this你可以这样试试

$('.videos').append( ['<li>',
    '<span>' + count + '</span> - ' ,
    '<a href="' + vList[i].player + '">' ,
        '<span class="title">' + videoTitle + '</span>' ,
    '</a>' ,
'</li>'].join('') );

From New Perspectives on HTML5, CSS, and JavaScript 6th Edition , Chapter 9 Getting Started with JavaScript:HTML5、CSS 和 JavaScript 的新视角第 6 版,第 9 章JavaScript 入门:

"If you want to break a text string into several lines, you can indicate that the text string continues on the next line by using the following backslash \\ character. "如果您想将一个文本字符串分成几行,您可以使用以下反斜杠\\字符指示该文本字符串在下一行继续。

Example of proper line break:正确换行的示例:
window.alert("Welcome \\
to Tulsa");

If you are rendering HTML using backticks and want to pass a variable inside it's very easy just add the backticks around the variable and concatenate it.如果您正在使用反引号渲染 HTML 并希望在内部传递一个变量,则非常简单,只需在变量周围添加反引号并将其连接起来即可。 let's take an eye on the below example让我们看看下面的例子

var x = 1; 
$(wrapper).append(`
                <div class="card">
                   <div class="card-body">
                      <h5 class="card-title">Plot `+ x +` </h5>
                   </div>
                </div>
               `);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM