When can i break lines in a string?
When can i break lines in a string?
sorry for the newbie question. I have this code, but i dont like it, its not very readable. I'm completely new to this and i'm not able to find an answer. I would like to spread the part following the append over multiple lines, but what is the correct syntax for this?
'buildHtml': function(data) {
$('.visibility-attributes').append('
},
"blah blah" (newline) +"more blah"
...– Niet the Dark Absol
Jul 3 at 9:33
"blah blah" (newline) +"more blah"
That being said, you generally shouldn't have that much HTML in your JavaScript files...
– Niet the Dark Absol
Jul 3 at 9:33
you can use the ` (the button left of 1 on standard uk qwerty keyboards) instead of the single quote and do it over multiple lines - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Pete
Jul 3 at 9:35
Sorry for the wrong language, yes, i meant JS. Thank you all for your fast answers, i will check out if i can find another way to use less html in JS, maybe one of my colleagues can help me. Thank you very much again, much appreciated <3
– SHRX
Jul 3 at 9:43
2 Answers
2
I suppose you are looking for this
Just write a backslash char at the end of every new line to consider the whole thing as one string. (Prevents head ache from + and "" ) Alternatively : You can write the structure in a hidden div (as a template) and fill the values in required html elements and copy the template to output div Be careful to replace the single quote ' with ` var myHtmlString = "
Bestand
" + data.stock.stocklevel + "
</div>
" + data.stock.orderable + "
</div>";
$('.visibility-attributes').append(myHtmlString )$("#hiddenDiv").find(".tab-product-attribute-name").html(data.stock.stocklevel);
//blah
//blah
$('.visibility-attributes').append($("#hiddenDiv").html());
Points for most elegant solution! :) You could also, rather than having a element filled with html. Use one element, with many contextualised data attributes.
– Benjamin James Kippax
Jul 3 at 10:33
'buildHtml': function(data) {
$('.visibility-attributes').append(`
${data.stock.stocklevel}
</div>
${data.stock.orderable}
</div>
`);
},
Note that template literals like this will not work at all in any version of IE
– Rory McCrossan
Jul 3 at 9:40
you can use Babel in IE : ) @Rory McCrossan
– xujizhong
Jul 3 at 9:42
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It looks like you might have confused Java with Javascript. They are different languages.
– khelwood
Jul 3 at 9:32