Convert HTML to Javascript String

大憨熊 提交于 2019-12-11 12:42:03

问题


I'm reading a book on how to create a SPA (single page applications). The author writes, if the IDE is any good then there will be a technique to convert a highlighted section of HTML and converted to a JavaScript string. How can this be done in Visual Studio 2013? An example of how I want the convert to work is below. Also it would be great to toggle back to the html.

HTML

<div class="spa-shell-head">
 <div class="spa-shell-head-logo"></div>
 <div class="spa-shell-head-acct"></div>
 <div class="spa-shell-head-search"></div>
</div>

JAVASCRIPT

var main_html = String()
+ '<div class="spa-shell-head">'
 + '<div class="spa-shell-head-logo"></div>'
 + '<div class="spa-shell-head-acct"></div>'
 + '<div class="spa-shell-head-search"></div>'
+ '</div>';

回答1:


Rather than converting HTML to a JS string, it would be much better to create the elements in JS and put them in the DOM. This would give you much more control, not create such a difficult to maintain/read code, create less problems, and be much faster:

var outerDiv = document.createElement("div");
outerDiv.className = "spa-shell-head";

var innerDivLogo = document.createElement("div");
innerDivLogo.className = "spa-shell-head-logo";

var innerDivAcct = document.createElement("div");
innerDivAcct.className = "spa-shell-head-acct";

var innerDivSearch = document.createElement("div");
innerDivSearch.className = "spa-shell-head-search";

outerDiv.appendChild(innerDivLogo);
outerDiv.appendChild(innerDivAcct);
outerDiv.appendChild(innerDivSearch);
document.body.appendChild(outerDiv);

The above creates the following:

https://jsfiddle.net/yfeLbhe4/



来源:https://stackoverflow.com/questions/25516154/convert-html-to-javascript-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!