最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

indentation - HTML String Line Break in Javascript - Stack Overflow

programmeradmin1浏览0评论

I am trying to output html with jQuery.

$('body').append('
<div>
  <div>
    <div></div>
  </div>
</div>
');

I want to indent the code in this way for higher readability. It works for php but not in JS, any ideas? I use notepad++ as editor.

I am trying to output html with jQuery.

$('body').append('
<div>
  <div>
    <div></div>
  </div>
</div>
');

I want to indent the code in this way for higher readability. It works for php but not in JS, any ideas? I use notepad++ as editor.

Share Improve this question asked Mar 26, 2011 at 19:27 benonebenone 6961 gold badge7 silver badges21 bronze badges 1
  • 1 what do you mean by it's not working in JS ? – Mohammed Swillam Commented Mar 26, 2011 at 19:30
Add a ment  | 

5 Answers 5

Reset to default 5

You should be using a templating system for that. No matter how much indentation you use, if you mix to much HTML and Javascript you will end-up will spaghetti code.

HTML

<script type="text/template" id="my-template">
    <div>
        <div>
            <div></div>
        </div>
    </div>
</script>

Javascript

$('body').append($('#my-template').html());

If you need more control over your template rendering, you need to use a library. I remend underscore.js, its not the best templating engine for javascript, but it's very lightweight and es with a great set of helper functions.

$('body').append('\n\
<div>\n\
  <div>\n\
    <div></div>\n\
  </div>\n\
</div>\n\
');
  • The \n is to insert a newline character in your string (so it’ll get outputted in your body element)
  • The final \ is Javascript's line continuation character, so you can keep your JS code indented without having to add + '' everywhere.

Try something like this:

$('body').append('\
<div>\
  <div>\
    <div>foo</div>\
  </div>\
</div>');

Have you tried using the Javascript string literals? "\n" is a newline, and "\t" is a tab.

If you want to indent, I suggest using the concatenation operator "+" whenever you want to add a new line in your code:

$('body').append(
'<div>' +
  '<div>' +
    '<div></div>' +
  '</div>' +
'</div>'
);
发布评论

评论列表(0)

  1. 暂无评论