簡體   English   中英

遍歷一個數組

[英]iterating through an abject array

我需要通過對象數組進行迭代的幫助。 我可以成功地遍歷變量'props',但不能使用'propsObjs'。

var props = {
    'dog':'true',
    'cat':'true',
    'mouse':'true'
};

var propsObjs = [
    {name:'dog', state:'true'},
    {name:'cat', state:'true'},
    {name:'mouse', state:'true'}
];

$.each(propsObjs, function (key, value) {
    $('#' + key + '-btn').click(function () {
    $(this).toggleClass('inactive-props');
    $('.' + key + ' ').toggleClass('hide');
});
});

這是原型的鏈接: http : //jsfiddle.net/readrefuse73/dZysP/10/

首先,委托函數$.each迭代具有indexvalue參數。 因此,在您的示例中, key是一個包含迭代索引的整數,而value是數組中包含的對象。 您需要的是這樣的東西:

$.each(propsObjs, function (index, value) {
    var key = value.name;
    $('#' + key + '-btn').click(function () {
    $(this).toggleClass('inactive-props');
    $('.' + key).toggleClass('hide');
});

第二個propsObjs是一個object數組。

因此,嘗試訪問對象屬性name將對您有所幫助

$.each(propsObjs, function (index, obj) {
    $('#' + obj.name+ '-btn').click(function () {
    $(this).toggleClass('inactive-props');
    $('.' + obj.name+ ' ').toggleClass('hide');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM