gpt4 book ai didi

javascript - 是否可以使用 pure.js 插入新的 HTML

转载 作者:行者123 更新时间:2023-11-29 17:19:57 25 4
gpt4 key购买 nike

我正在搜索从 JSON 数据文件开始呈现 HTML 模板的东西。

问题是我要搜索的插件/框架/库必须自己创建 <html>模板结构,从非常简单的事情开始。

例如我有一个像这样的简单 html:

<ul>
<li><li>
</ul>

和这样的 json:

{
"mylist":{
"listone":
{"img" : "/img/pippo.gif" ,
"text1" : "pluto",
"text2" : "topolino",
"link" : "http://www.sito.it"
},
"listtwo":
{"img" : "/img/pippo.gif" ,
"text1" : "pluto",
"text2" : "topolino",
"link" : "http://www.sito.it"
}
}
}

我希望数据像这样呈现在我的文档中:

<ul>
<li>
<img src="/img/pippo.gif" />
<h1>pluto</h1>
<p><a href="http:://www.sito.it>topolino</a></p>
</li>
</ul>

如果我已经掌握了整个结构,我可以使用 pure.js像往常一样,但是,因为我在 li 中没有内部标签,我可以用 pure.js 注入(inject) HTML 代码吗?指令?或者只有 JsRender 才有可能或类似的?

最佳答案

纯 JS 允许您使用 JavaScript 函数 directives .无论从该函数返回什么,都将用作指令的值。

The argument of the function is an object with the following properties:

  • context : This is the full JSON that was passed for transformation
  • item* : the current loop item
  • items* : all the items of the loop
  • pos* : the current position in the loop. An integer when iterating an array, a property name iterating on a collection

下面的例子展示了如何做到这一点。

var data = {
"img": "/img/pippo.gif",
"text1": "pluto",
"text2": "topolino",
"link": "http://www.sito.it"
}

var directive = {
'li': function (arg) {
return "<img src=\""+arg.context.img+"\" /><h1>"
+arg.context.text1+"</h1><p><a href=\""
+arg.context.link+"\">"+arg.context.text2+"</a></p>"
}
}

$('ul').render(data, directive);

给定的 HTML:

<ul><li></li></ul>

会变成下图(渲染后):

<ul>
<li>
<img src="/img/pippo.gif">
<h1>pluto</h1>
<p>
<a href="http://www.sito.it">topolino</a>
</p>
</li>
</ul>

希望对您有所帮助。

关于javascript - 是否可以使用 pure.js 插入新的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13608602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com