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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19313096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:38:44  来源:igfitidea点击:

Breaking a string into multiple lines inside a javascript code

javascriptjqueryhtmlembedded-resource

提问by Simone

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();method.

基本上,这是一段 html 代码,我试图通过调用 jQuery 的.append();方法将其附加到页面。

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?

有什么建议?

回答by Benjamin Gruenbaum

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 .replacechain.

当然,如果你发现自己经常这样做,你可以使用模板引擎而不是.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>`;

回答by ProGM

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>');

回答by Sergio

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. Its faster:

并且换行不会有问题。在 ES6 之前,我主要使用数组并将它们连接起来。它更快:

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

Old answer:

旧答案:

In javascript you cannot break lines without concatenating them with a +or using \. Try this:

在 javascript 中,如果不使用 a+或 using将它们连接起来,就不能断行\。尝试这个:

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

回答by ScaryLooking

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);

回答by rab

you can try like this

你可以这样试试

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