3

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?

4 Answers 4

5

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>';
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

@Brad: That's different. Backslash-newline does not produce a newline in the actual string; it is only a way to include a newline in the string-literal in the source-code.
2

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

Comments

2

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.

2 Comments

jQuery has it's good points and i use it religiously, but i find there are times when putting markup in is necessary.
@moonwave99, I think you mean append. It could also be written $('<li>').append($('<a>', {href: '#dalink'})).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.