javascript - 通过 obj 键访问属性

标签 javascript jquery html

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

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

在我的示例中,您会注意到“test123”。这是我还不知道该怎么做的部分。这引出了我的问题:

为了动态更新每个目标,我创建了一个对象(参见:this.classNames),其中包含所有类名和属性名作为键。如果我有 key (例如:用户),我可以访问 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>

最佳答案

如果我理解正确,你要做的是在 的异步更新循环中查找 $this 对应于 className 的属性.replaceWith 行。如果是这样,改变

.replaceWith('test123");

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

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

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

Updated Fiddle

关于javascript - 通过 obj 键访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29672426/

相关文章:

javascript - 请求的模块不提供名为

html - 无法滚动到容器溢出的 flex 元素顶部

javascript - 第二个 $(document).ready 事件 jQuery

javascript - 使用 keyup 事件使 jquery 图标可见

javascript - 如何在不破坏此 DIV 的悬停区域的情况下在 DIV 上放置一些文本?

javascript - 使用 Javascript 按行数据对 HTML 表格进行排序

javascript - 从输入中获取值并替换

javascript - 侧边栏折叠一秒钟并在页面加载时展开

javascript - 限制显示数组对象

javascript - 在 JavaScript 函数中间暂停