I am trying to output html with jQuery.
$('body').append('
<div>
<div>
<div></div>开发者_如何学Python;
</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.
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 recommend underscore.js, its not the best templating engine for javascript, but it's very lightweight and comes 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>'
);
精彩评论