如何使用jQuery动态调用JavaScript对象上的属性 [英] How to dynamic call property on javascript object with jQuery
本文介绍了如何使用jQuery动态调用JavaScript对象上的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好! 我说了一个带有一些属性的javascript对象
Hallo all. I got a javascript object with some propeties let's say
function Animal() {
this.id;
this.name;
我需要以动态方式调用id函数来获取并设置其值:类似这样的
I need to call id function in a dynamic way to get and set its value: something like this
Animal animal = new Animal();
var propertyName = "id";
animal.+propertyName = "name";
有一种优雅的方法吗?使用jQuery吗?
Is there an elegant way to do it? With jQuery?
亲切的问候
马西莫(Massimo)
Massimo
推荐答案
除对象语法外,在JavaScript中,您还可以使用类似数组的语法来查询对象属性.因此,在您的情况下:
Apart from object syntax, in JavaScript you can also use an array-like syntax to query object properties. So in your case:
function Animal() { this.id; this.name };
Animal animal = new Animal();
animal.id = "testId";
var propertyName = "id";
alert(animal[propertyName]); // this should alert the value "testId";
这是一篇包含更多详细信息的文章: http://www.quirksmode.org/js/associative .html
Here's an article with more details: http://www.quirksmode.org/js/associative.html
这篇关于如何使用jQuery动态调用JavaScript对象上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文