我试图获取单击它的列表项的颜色。当颜色是红色时,我想给它加一些约束。怎么做,我不明白。
if($("#listbox option:selected").css("color")=="red"){
}
我有一个列表框,里面有一些红色的项目。我想阻止用户选择那些红色的项目。
请帮帮我。
正如Pete建议的那样,使用data属性是一种更好更简单的方法:http://jsfiddle.net/aamir/tq9W8/5/
$('#listbox option:eq(0)').css('color', 'red').data('color', 'red');
$('#listbox').change(function () {
if ($(this).find("option:selected").data('color') == 'red') {
alert('color is red');
} else {
alert('other options');
}
});
或者你可以试试:http://jsfiddle.net/aamir/tq9W8/4/
$('#listbox option:eq(0)').css('color', 'red');
function checkColorByName(ele, colorName) {
var tempDiv = $('<div>').css("color", colorName).hide().appendTo('body');
console.log(tempDiv.css('color'));
var bol = tempDiv.css('color') == ele.css('color');
tempDiv.remove();
return bol;
}
$('#listbox').change(function () {
if (checkColorByName($(this).find("option:selected"), 'red')) {
alert('color is red');
} else {
alert('other options');
}
});
你的代码很好。
如果不工作,执行console.log($("#listbox option:selected").css("color")=="red");
如果它说undefined,则color属性没有在选项上设置,但可能在#listbox
上设置。(Try $("#listbox option:selected").parent().css("color")=="red")
)