[英]What is the best way to repeat html code using javascript object?
Using some js object like 使用一些js对象
links = {
link1: "Text1",
link2: "Text2",
link3: "Text3"
};
I want to create several <a>
elements with href
from keys and content from values, like 我想用键的
href
和值的内容创建几个<a>
元素,例如
<a href="link1">Text1</a>
<a href="link2">Text2</a>
<a href="link3">Text3</a>
What is the best and the shortest way to do it using js or some popular js frameworks? 使用js或一些流行的js框架实现它的最佳和最短方法是什么?
you want to use for loop in javascript. 您要在JavaScript中使用for循环。
HTML: HTML:
<p id="demo" />
JS: JS:
links = {
link1: "Text1",
link2: "Text2",
link3: "Text3"
};
var element, filling = "";
for (element in links) {
filling += "<a href=\"{0}\">{1}</a>"
.replace("{0}", element)
.replace("{1}", links[element]);
}
document.getElementById("demo").innerHTML = filling;
See the demo here: http://jsfiddle.net/0subxy9m/1/ 在此处查看演示: http : //jsfiddle.net/0subxy9m/1/
with Angular for example and your links object 以Angular为例,您的链接对象
HTML HTML
<li ng-repeat="(link,text) in links">
<a href="http://example.com/{{link}}">{{text}}</a>
</li>
JS JS
$scope.links = {
link1: "Text1",
link2: "Text2",
link3: "Text3"
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.