JavaScript对象属性-将它们连接在一起吗? [英] JavaScript object properties - connect them together?

查看:81
本文介绍了JavaScript对象属性-将它们连接在一起吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个数组中有3个对象.

I have 3 objects in an array.

myArray = [
{name: "iPhone", link: "www.apple.com"},
{name: "Nokia", link: "www.nokia.com"},
{name: "Google", link: "www.Google.com"}
]

如何进行循环并将属性放在一起显示在页面上,如下所示:

How to make a loop and put properties together to display on page, like this:

iPhone 诺基亚 谷歌

iPhone Nokia Google

当您点击链接时拥有链接

And have links when you click on them

谢谢!

推荐答案

使用纯JS,就像这样:

With pure JS, it would be like that :

for(var i=0;i<myArray.length;i++){
    var a = document.createElement('a');
    a.href= myArray[i].link;
    a.text= myArray[i].name;
    document.body.appendChild(a);
}

但是使用jQuery会容易得多

But it is much easier with jQuery:

您可以使用jQuery .each().它将遍历您的数组,您可以使用this访问对象属性.

You can use jQuery .each(). It will loop through your array and you can access object properties with this.

要建立链接,请创建一个a元素,并使用.attr().text()

To make a link, you create a a element and assing his value with .attr() and .text()

$.each(myArray, function(){
    var a = $('<a/>'); //The element itself
    a.attr('href', this.link) //The HREF
    a.text(this.name) //The text
    $('body').append(a) //Append to the body
})

这篇关于JavaScript对象属性-将它们连接在一起吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆