将“每个”替换为“更改”
$('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
支持django admin中的自定义CSS。
而且我认为正确的CSS属性是:
'background-color'。
backgroundColor是javascript,应按以下方式使用:
$(this).css({backgroundColor:color});但是它似乎仍然可以正常工作,所以没什么大不了的。编辑:
如果要在页面加载时初始化脚本,则只需在后面添加.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();


