简体   繁体   中英

Creating HTML Content In a Variable in Javascript

I have a javascript variable I need to create like this:

var HTMLContent = '<div class="className">HTML Content</div>';

How can I format it in an easier to read format because I'm going to want to create multiple lines of HTML.

eg

var HTMLContent = '
<div class="className">
  HTML Content
</div>
';

Is something like that possible?

It would also be good if I could import via URL eg var HTMLContent = 'http://domain.com/page.html';

 var longStr = "You can split\
 the string onto multiple lines\
 like so";

An example using your HTML would be:

var longStr = 
    '<div class="className">\
        HTML Content\
    </div>';

To load external HTML, check out jQuery's load method :

$('#result').load('ajax/test.html');

In your page markup, add a hidden template div, like:

<div id="contentTemplate" style="display: none;">
    <div class="className">
        HTML_CONTENT
    </div>
</div>

...then in your JavaScript, you can do something like:

var newContent = 'The content for the new element';
var templateContent = document.getElementById("contentTemplate").innerHTML;
var htmlContent = templateContent.replace("HTML_CONTENT", newContent);

You could also use an AJAX request to pull the value of newContent from a URL to get your dynamic content loading working. If you plan on doing this, however, then I suggest you investigate using a framework like jQuery , which can greatly simplify this process.

You can also use backticks

 function myFunc() { var HTMLContent =` <div class="className"> <div>HTML Content</div> </div> `; document.getElementById('demo').innerHTML = (HTMLContent); } myFunc() 
 <div id="demo"></div> 

var HTMLContent = "" +
"<div class=\"className\">\n" +
"    HTML Content\n" +
"</div>\n" +
"";

This way, the script that writes it it pretty and the code it writes will be pretty too if someone were to view-source.

You can use escape characters:

var HTMLContent = '<div class="className">\\n\\tHTML Content\\n</div>';

I may have misinterpretted the question, you want the javascript to be more readable, not the html stored in the variable?

var HTMLContent = 
    '<div class="className">' +
    'HTML Content' +
    '</div>';

You can do something like:

 var HTMLContent = '<div class="ClassName">' + 
   'HTML Content' +
    '</div>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM