【发布时间】:2015-08-19 00:52:19
【问题描述】:
我正在尝试根据其内容交换某些特定 div 的背景颜色。
当他们的输入是“生活方式”或“政治”或“经济”或“本地”或“体育”或“新闻”时,他们的背景颜色应该交换。
var colorInput = document.getElementById('views-field-field-section').textContent;
switch (colorInput) {
case 'Lifestyle':
document.getElementById('views-field-field-section').style.backgroundColor = '#9518b8';
break;
case 'Local':
document.getElementById('views-field-field-section').style.backgroundColor = '#009fe3';
break;
case 'Sports':
document.getElementById('views-field-field-section').style.backgroundColor = '#95c11f';
break;
case 'Economy':
document.getElementById('views-field-field-section').style.backgroundColor = '#d40d10';
break;
case: 'Politics':
document.getElementById('views-field-field-section').style.backgroundColor = '#ffcc00';
break;
default:
break;
}
【问题讨论】:
-
你不应该在多个元素上使用相同的 id,它是无效的。使用不同的 id。
-
正如我在您的 jsfiddle 上看到的,您的 html 代码中的 div 元素中有空格,所以只需
trim您的colorInput。 -
id 必须是唯一的。
-
你会用jQuery吗?还是 mootools 是必需品?
-
唯一ID是我的问题。它必须是相同的 ID。否则我只能通过 CSS 交换颜色。
标签: javascript css switch-statement background-color