我正在尝试让我的背景颜色根据所选选项进行更改。在他们选择所需的选项后,什么也没有发生。这是我的代码;
HTML代码;
<select id="importance" onchange="this.className=this.options[this.selectedIndex].className" class="low">
<option class="low" value="low">Low</option>
<option class="medium" value="medium">Medium</option>
<option class="high" value="high">High</option>
<option class="urgentap" value="urgent">Urgent</option>
</select>
J查询;
var projectCreate = $('#createP').on('click', function(){
var name = $('.project-form input#name').val(),
date = $('.project-form input#date').val(),
time = $('.project-form input#time').val(),
description = $('.project-form textarea#description').val(),
importance = $('.project-form select#importance option:selected').val();
if(importance == "Low")
$(".item").css('background','lightblue');
else if ($('#importance option:selected').text() == "Medium")
$(".item").css('background','yellow');
else if ($('#importance option:selected').text() == "High")
$(".item").css('background','orange');
else if ($('#importance option:selected').text() == "Urgent")
$(".item").css('background','red');
else
alert('test');
$.ajax({
url: 'xhr/new_project.php',
data: {
projectName: name,
projectDescription: description,
dueDate: date,
time: time,
status: importance
},
type: 'post',
dataType: 'json',
success: function(response){
if(response.error){
$( ".error" ).empty(),
$( ".error" ).fadeIn(),
$(".error").append('<h2 class="error-text">' + response.error + '</h2>').fadeIn(),
$( ".error" ).delay(1500),
$( ".error" ).fadeOut();
}else{
loadApp();
}
}
});
return false;
});
我做错了什么吗?提前致谢!
最佳答案
这里有很多额外的疯狂行为可能对您的事业没有帮助。
让我们从检测选择框的更改事件开始。首先,我们想要不显眼的代码,所以从您的元素中删除 JavaScript:
<select id="importance" class="low">
<option class="low" value="low">Low</option>
<option class="medium" value="medium">Medium</option>
<option class="high" value="high">High</option>
<option class="urgentap" value="urgent">Urgent</option>
</select>
然后你的 jQuery 代码可以这样做:
$( "#importance" ).change(function() {
var importance = $('option:selected', $(this)).val();
});
接下来,我建议将您的背景颜色包含在 CSS 类中,这样您就无需考虑单独应用哪种颜色。所以创建一些这样的类:
.importance-low { background-color: lightblue; }
.importance-medium { background-color: yellow; }
.importance-high { background-color: orange; }
.importance-urgent { background-color: red; }
从那里您可以将您的类作为上述 .change()
函数的一部分应用于任何元素:
$('.item').removeClass('importance-low importance-medium importance-high importance-urgent').addClass('importance-' + importance);
这将从您的元素中清除任何先前选择的类/值并添加新选择的。
关于jquery - 更改所选选项的 css 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120674/