开发者

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.

e.g.

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

Is something like that possible?

It would also be good if I could import via URL e.g. 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">' +
    'HTML Content' +
    '</div>';


You can do something like:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜