Jquery 更改选定选项上的css元素
我正试图使我的背景色根据选定的选项进行更改。在他们选择所需选项后,什么也不会发生。这是我的密码 Html代码Jquery 更改选定选项上的css元素,jquery,css,Jquery,Css,我正试图使我的背景色根据选定的选项进行更改。在他们选择所需选项后,什么也不会发生。这是我的密码 Html代码 <select id="importance" onchange="this.className=this.options[this.selectedIndex].className" class="low"> <option class="low" value="low">Low</option> <option class="
<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>
Jquery
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>
接下来,我建议在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);
这将清除项目中以前选择的所有类/值,并添加新选择的类。我想,您需要选择元素的onchange事件……我是否建议为每个重要情况添加css类,并将重要值作为类应用于.item?
$('.item').removeClass('importance-low importance-medium importance-high importance-urgent').addClass('importance-' + importance);