通过obj键访问属性

时间:2015-04-16 10:48:09

标签: javascript jquery html

我将我的工作简化为这个小例子。

我正在为类“myClass”编写一个库,该类具有一些属性(用户,名称,权重,高度)和目标列表(=元素ID)。我的想法是,如果我更新我的课程,目标中的所有数据都会更新。

在我的例子中你会注意到“test123”。这是我还不知道该怎么做的部分。这让我们想到了我的问题:

要动态更新每个目标,我创建了一个对象(请参阅:this.classNames),其中包含所有类名和属性名作为键。如果我有密钥(例如:用户),我可以访问this.user吗?这甚至可能吗?

这是一个有效的jsfiddle:Demo

JS

(function () {
    var myClass = function (o) {
        if (!(this instanceof myClass)) {
            return new myClass(o);
        }
        if (typeof o === 'undefined') {
            o = {};
        };

        this.user = o.user || 'unknown';
        this.name = o.name || 'unknown';
        this.weight = o.weight || 'unknown';
        this.height = o.height || 'unknown';

        //targets -- strings that start with #
        this.targets = [];

        this.classNames = {
            user: '.user',
            name: '.name',
            weight: '.weight',
            height: '.height'
        };

    };
    myClass.fn = myClass.prototype = {
        init: function () {}
    };
    //must start with #
    myClass.fn.addTarget = function (tar) {
        this.targets.push(tar);
        return this;
    };
    myClass.fn.update = function (o, callback) {
        if (typeof o === 'undefined') {
            o = {};
        }

        this.user = o.user || this.user;
        this.name = o.name || this.name;
        this.weight = o.weight || this.weight;
        this.height = o.height || this.height;

        var $this = this;

        //asynchronous update
        setTimeout(function () {
            //Here I loop through all the targets                
            $.each($this.targets, function (index, value) {

                console.log(index + ' ' + value);

                //Here I loop through all the classNames
                $.each($this.classNames, function (key, className) {
                    console.log(key + ' ' + className);
                    //I only want to replace text 
                    $(value).find(className).contents().filter(function () {
                        return (this.nodeType == 3);
                    //=== Problem Here=== With "key" how do I access attributes?
                    }).replaceWith('test123');

                });
            });
            if (!(typeof callback === 'undefined')) {
                callback();
            }
        }, 0);
    };

    //exporting lib
    window.myClass = myClass;
})();
myClass().addTarget('#target1').addTarget('#target2').update({
    user: 'Grimbode',
    name: 'Kevin'
}, function () {
    console.log('update has finished');
});

HTML

<div id="target1">
    <div class="user">a</div>
    <div class="name">b</div>
    <div class="weight">c</div>
    <div class="height">d</div>
</div>
<div id="target2">
    <div class="user">e</div>
    <div class="name">f</div>
    <div class="weight">g</div>
    <div class="height">h</div>
</div>

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您要执行的操作是查找$this上与className行上的异步更新循环内.replaceWith对应的属性。如果是,请更改

.replaceWith('test123");

.replaceWith($this[className.substring(1)]);

在JavaScript中,您可以使用点表示法和属性名称文字(例如obj.foo),或使用括号表示法和属性名称​​ string 来访问属性名称(例如, obj["foo"])。在后一种情况下,字符串可以是任何表达式的结果。

在您的代码中,className上有一个前导.(例如".user"),因此我们要删除它(.substring(1))以获取属性名称(例如,"user"),然后在[...]中使用它来查找属性值。

Updated Fiddle