Satch3000
Satch3000

Reputation: 49384

JQuery / Javascript issues with whitespace

I am having problems with javascript not allowing my to use whitespace so I'm having to squash all the code making it hard to read.

Sample A: - Working:

output += '<li><a href="#">test here</a><li>';


Sample B: - Not Working:

output += '<li>
           <a href="#">test here</a>
           </li>';

Is there a way where I could get the above for work without having to first squash it all together?

Upvotes: 3

Views: 113

Answers (4)

moonwave99
moonwave99

Reputation: 22817

Don't write markup in JS, unless it's just a couple of tags.

Consider creating elements in jQuery:

var output = $('<li>').append(
                $('<a>').attr('href', '#dalink')
            );

or much better, use templating, i.e. markup templates with placeholders and little presentational logic like loops for populating lists.

Upvotes: 2

Lews Therin
Lews Therin

Reputation: 10995

You may want to check out multi line strings in javascript. Like so: http://www.electrictoolbox.com/javascript-multi-line-strings/

For some code example, try:

 output += '<li>\
               <a href="#">test here</a>\
               </li>'

Upvotes: 4

Omer Perry
Omer Perry

Reputation: 108

The solution is a backspace:

output += '<li>\
           <a href="#">test here</a>\
           </li>';



EDIT
If you do want to keep the newlines, put \n before the \.

Upvotes: 2

Brian Hoover
Brian Hoover

Reputation: 7991

You can do something like this. I find it slightly easier to read, but harder to maintain.

output += '<li>' + 
           '<a href="#">test here</a>' + 
           '</li>';

Upvotes: 5

Related Questions