1

我需要定义包含很长 html 代码的 javascript 变量。

这是一个简短的例子:

var text = "Select one item:<br>";
text += "<ul class='thumbnails'><li class='span3'><a href='#' class='thumbnail'><img src='http://placehold.it/260x180' alt=''></a></li></ul>";

由于 html 会长得多,我宁愿在纯 html 中工作,而不是将文本附加到 javascript 字符串。

我想创建一个单独的 html 文件,但我想这需要 Ajax 调用来获取其内容。处理这个问题的最佳方法是什么?

4

4 回答 4

1

As N.Zakas said on "maintainable javascript" book, you should «keep html out of javascript» to promote high mantainability of the code through loose coupling of UI layers.

Beside the ajax solution you could also place the markup as a comment in the html file and read it via javascript (as a regular DOM node) or you could use some kind of microtemplating system (e.g. handlebars) and place your markup in a script block (the idea is to put markup where is expected to be found and not into javascript logic)

于 2012-08-10T10:38:55.110 回答
1

One possible solution is to use templates. There are a few JavaScript libraries that provide templating, underscore.js is one: http://underscorejs.org/#template, or more details on how to use it for templating http://www.headspring.com/blog/developer-deep-dive/an-underscore-templates-primer/

Plus underscore is great for a number of other things.

于 2012-08-10T10:39:17.263 回答
0

Instead of constructing HTML in Javascript as a string, I would rather suggest you to emit those html elements in the page itself and hide while loading. Then in Javascript, you could select that container and display it.

于 2012-08-10T10:38:06.377 回答
0

You could break up the text into actual HTML objects.

var thumbnailsUL = document.createElement('ul');
for (index in {your-thumbnails-list}) {
  var thumbnail = document.createElement('li');
  thumbnail.innerHTML = {whatever you need, more objects or html as text};
  thumbnailsUL.appendChild(thumbnail);
}

Ideally though, there is no reason to build this IN JavaScript - can you not emit it from the server?

于 2012-08-10T10:39:48.593 回答