相关疑难解决方法(0)

使用内置DOM方法或Prototype从HTML字符串创建新的DOM元素

我有一个表示元素的HTML字符串:'<li>text</li>'.我想将它附加到DOM中的一个元素(ul在我的例子中).如何使用Prototype或DOM方法执行此操作?

(我知道我可以在jQuery中轻松完成这个,但不幸的是我们没有使用jQuery.)

javascript dom prototypejs

555
推荐指数
15
解决办法
53万
查看次数

Mustache.js外部模板(不带jQuery)

我正在编写一个没有jQuery作为依赖项的组件,我希望找到一种方法来加载一个没有jQuery的外部Mustache.js模板.使用jQuery的$.get方法似乎有效,但我试图在vanilla JS中做到这一点.

我尝试使用an XMLHttpRequest并将模板附加到主体,然后使用我的JSON对其进行保湿,但是当我的JS尝试将JSON放入模板中时,模板不存在水合(cannot read property innerHTML of null).这是我的代码(在CoffeeScript中,test.js是胡子模板):

req2 = new XMLHttpRequest()
req2.onload = ->
  foo = document.getElementById('thatsmyjam')
  templ = document.createTextNode(this.responseText)
  foo.insertAdjacentHTML('beforeEnd', templ)
req2.open('GET', 'test.js', { async: false})
req2.responseType = 'document'
req2.send()
Run Code Online (Sandbox Code Playgroud)

这会[object Text]在DOM中添加文字文本而不是将其视为HTML,因此它似乎是在评估HTML字符串而不是将其渲染为HTML.

可能有更好的方法.我基本上试图将我的App(获取JSON),mustache.js和模板组合成一个连接的缩小文件,以便作为UI小部件进行分发.

我也研究了类似Hogan.js的东西来预编译模板,但感觉很复杂,而且我无法在这个项目中使用Node.

更新

如果我将上面的CoffeeScript更新为:

req2 = new XMLHttpRequest()
req2.onload = ->
  foo = document.getElementById('thatsmyjam')
  window.templ = document.createTextNode(this.responseText)
  foo.insertAdjacentHTML('beforeEnd', templ)
req2.open('GET', 'test.js', { async: false})
req2.send()
Run Code Online (Sandbox Code Playgroud)

然后它被视为我的应用程序中尝试呈现模板的相关部分中的字符串:

populateDom: =>
    self = …
Run Code Online (Sandbox Code Playgroud)

javascript mustache

5
推荐指数
1
解决办法
1621
查看次数

标签 统计

javascript ×2

dom ×1

mustache ×1

prototypejs ×1