Using some js object like
links = {
link1: "Text1",
link2: "Text2",
link3: "Text3"
};
I want to create several <a>
elements with href
from keys and content from values, like
<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?
you want to use for loop in javascript.
HTML:
<p id="demo" />
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/
with Angular for example and your links object
HTML
<li ng-repeat="(link,text) in links">
<a href="http://example.com/{{link}}">{{text}}</a>
</li>
JS
$scope.links = {
link1: "Text1",
link2: "Text2",
link3: "Text3"
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.