简体   繁体   English

使用javascript对象重复html代码的最佳方法是什么?

[英]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"
};

plnkr demo here 这里的plnkr演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 JavaScript 动态生成 HTML 元素列表的最佳方法是什么? - What is the best way to generate a list of HTML elements dynamically using JavaScript? 使用 javascript 滑动 html 的最佳方式是什么? - What is the best way of sliding section of html using javascript? 使用 javascript 在 html 中添加 SVG 的最佳方法是什么? - What is the best way to add SVG in html using javascript? 使用 javascript 编码选择模式为 Windows 的最佳方法是什么? - What is be the best way to code selecting mode as Windows using javascript? 使用lodash或JavaScript过滤此对象的最佳方法是什么? - What is the best way to filter this object using lodash or JavaScript? 这是使用面向对象方法在 Javascript 中编写这个小型计算器的最佳方式吗? - Is this the best way to code this small calculator in Javascript using Object Oriented approach? 将 javascript 对象分配给 html 元素的最佳方法 - Best way to assign a javascript object to html element 在JavaScript中格式化HTML,CSS和JavaScript代码的最佳方法是什么? - What's the best way to format HTML, CSS and JavaScript code within a JavaScript 在JavaScript中删除对象的最佳方法是什么? - What is the best way to delete an object in JavaScript? 在Javascript中检查对象是否为数组的最佳方法是什么? - What is the best way to check if an object is an array or not in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM