将“每个”替换为“更改”
$('select[id$=-status][id^=id_item-]').change(
function (){
var color = $('option:selected',this).css('background-color');
$(this).css('background-color',color);
}
).change();
这适用于 Chrome。
另请参阅:http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions
支持 django admin 中的自定义 css。
我相信正确的 css 属性是:'background-color'
.
backgroundColor
是 javascript 并且应该像这样使用:$(this).css({backgroundColor:color});
但无论如何它似乎都有效,所以没什么大不了的。
EDIT:
如果你想在页面加载时初始化脚本,你可以在后面添加 .change() 。
参见代码。
我还在 Firefox 中测试了这一点,我也看到了这种奇怪的行为(蓝色,带有蓝色?)。
另一个编辑:
好的,下面是 Firefox 的快速修复:
$('select[id$=-status][id^=id_item-]').children().each(function (){
if($(this).val() == 0){
$(this).attr('style', 'background-color:white;');
}
if($(this).val() == 1){
$(this).attr('style', 'background-color:green;');
}
if($(this).val() == 2){
$(this).attr('style', 'background-color:red;');
}
if($(this).val() == 3){
$(this).attr('style', 'background-color:orange;');
}
});
$('select[id$=-status][id^=id_item-]').change(function (){
var style = $(this).find('option:selected').attr('style');
$(this).attr('style', style);
}).change();
最后编辑:
如果你使用 css,你甚至可以这样做:
<style>
select option,
select {
background-color:white;
}
select option[value="1"],
select.o1
{
background-color:green;
}
select option[value="2"],
select.o2
{
background-color:red;
}
select option[value="3"],
select.o3
{
background-color:orange;
}
</style>
<script>
$('select[id$=-status][id^=id_item-]').change(function (){
var color = $(this).find('option:selected').val();
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
}).change();
</script>
另一个编辑:
我遇到了这个,发现我可以缩短它,所以我这样做只是为了好玩:
$('select[id$=-status][id^=id_item-]').children().each(function() {
var colors = ['white', 'green', 'red', 'orange'];
$(this).attr('style', 'background-color:' + colors[$(this).val()] + ';');
});
$('select[id$=-status][id^=id_item-]').change(function() {
$(this).attr('style', $(this).find('option:selected').attr('style'));
}).change();