如何使用我的JS变量作为数组键?

时间:2015-06-23 19:37:40

标签: javascript jquery css

到目前为止,这是我的jQuery:

var themes = {};
themes['blue'] = {
    'background': 'blue',
    'color': 'white',
};
themes['red'] = {
    'background': 'red',
    'color': 'green',
};

$("#colors").change(function() {
    var theme = $(this).val();
    $("body").css(themes[theme]);

基本上,我希望根据用户从#colors下拉菜单中选择的内容来更改css:

<select id="colors">
    <option selected="selected">Colors:</option>
    <option value="Blue">Blue</option>
    <option value="Red">Red</option>
</select>

以下工作正常:

var themes = {
    blue: {
        'background': 'blue',
    }
};

$("#colors").change(function() {
    var color = themes['blue'];
    $("body").css(color);
});

但我想增加对蓝色的支持,而不仅仅是背景。任何建议将不胜感激!

3 个答案:

答案 0 :(得分:3)

在您的选项中,您使用了BlueRed,但在对象中,属性名称是小写的。

所以要么在任何地方使用相同的案例,要么使用toLowerCase

var theme = $(this).val().toLowerCase();
$("body").css(themes[theme]);

&#13;
&#13;
var themes = {
  blue: {
    background: 'blue',
    color: 'white',
  },
  red: {
    background: 'red',
    color: 'green',
  }
};
document.getElementById('colors').onchange = function() {
  var theme = this.value.toLowerCase();
  Object.assign(document.body.style, themes[theme]);
}
&#13;
<select id="colors">
  <option selected="selected">Colors:</option>
  <option value="Blue">Blue</option>
  <option value="Red">Red</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用小写值,因为对象键是小写的。

var themes = {
    blue: {
        background: 'blue'
    },

    red: {
        background: 'red',
        color: 'white'
    }
};


$("#colors").change(function() {
    var value = $(this).val().toLowerCase();
    $('body').css(themes[value]);
});

答案 2 :(得分:0)

通过支持应用程序的多种颜色主题,我们还可以采用更强大的方法,如下所示。

更新您的html并在头部添加以下内容

<link id="theme-scheme" rel="stylesheet"/>

现在,为每个主题创建其特定的主题 - {theme_name} .css ,例如对于蓝色,您可以使用theme-blue.css,对于红色,您可以使用theme-red.css

所以,现在更新你的功能,如下所示

$("#colors").change(function() {
    var theme = $(this).val().toLowerCase();
    $('#theme-scheme').attr('href', '/your_base_path/theme-' + color + '.css');
});

这种方法使您可以灵活地在任何元素上添加任何样式,而不必为每种样式添加脚本。

相关问题