0

我正在编写一个循环遍历对象以首先获取元素的脚本,然后我试图循环遍历元素的值,以便我可以更改 CSS。这是脚本:

$(document).ready(function() {
var carParts = {
    doors: {
        flDoor: 'LOCKED',
        blDoor: 'LOCKED',
        frDoor: 'LOCKED',
        brDoor: 'LOCKED'
    }
}
var lights = 'OFF';
if (lights === 'OFF') {
    $('.lights').css("display", "none");
}

for(var i in carParts.doors) {
    for(var key in carParts.doors) {
        var value = carParts.doors[key];
        console.log(value);
        if (value === 'locked') {
            $('.'+i+'-open').css("display", "none");
        }
    }
}
})

所以我想遍历 carparts.door 对象并获取实际的 flDoor、blDoor、frDoor、brDoor。在最后的 jquery 行中需要这些名称来分配正确的类名。我不希望那条线触发,除非实际值被锁定。我是 javascript 的新手,仍在学习。感谢您对代码的任何反馈。

4

1 回答 1

1

Working FIDDLE Demo

The LOCKED is in uppercase. You are comparing with the lowercase. Try this:

if (value === 'LOCKED') {
    //
}

And why you have two loops? One is enough.

HTML

<div class="flDoor-open">flDoor</div>
<div class="blDoor-open">blDoor</div>
<div class="frDoor-open">frDoor</div>
<div class="brDoor-open">brDoor</div>

JavaScript

$(function () {
    var carParts = {
        doors: {
            flDoor: 'OPENED',
            blDoor: 'OPENED',
            frDoor: 'LOCKED',
            brDoor: 'LOCKED'
        }
    };

    for (var key in carParts.doors) {
        var value = carParts.doors[key];

        if (value === 'LOCKED') {
            $('.' + key + '-open').css("display", "none");
        }
    }
});
于 2013-05-16T14:40:59.667 回答