我正在尝试向select
元素添加一个类,具体取决于所选的option
。
HTML
<select class="wordpress">
<option value="1" class="wordpress">Hello</option>
<option value="2" class="joomla">2222</option>
<option value="3" class="wordpress">33333</option>
<option value="4" class="joomla">44444</option>
</select>
CSS
select{
margin-top:50px;
padding:10px;
font-size:30px;
border:1px solid #ccc;
}
.wordpress{
background:url('http://muabanraovat.com/images/imgWordpress32.png') no-repeat center left transparent;
padding-left:35px;
}
.joomla{
background:url('https://a6a8g7g5.ssl.hwcdn.net/icons/22/216447/icon.png') no-repeat center left transparent;
padding-left:35px;
}
JS
$(document).ready(function($){
$('select').change(function(){
$(this).removeClass().addClass('wordpress');
});
});
CSS Deck:http://cssdeck.com/labs/vmbenx2c
答案 0 :(得分:0)
cell.detailTextLabel.frame.origin.y, 44.0, 44.0);
&#13;
$(document).ready(function($){
$('select').change(function(){
$(this).removeClass().addClass($(this).children('option[value="' + $(this).val() + '"]').attr('class'));
});
});
&#13;
select{
margin-top:50px;
padding:10px;
font-size:30px;
border:1px solid #ccc;
}
.wordpress{
background:url('http://muabanraovat.com/images/imgWordpress32.png') no-repeat center left transparent;
padding-left:35px;
}
.joomla{
background:url('https://a6a8g7g5.ssl.hwcdn.net/icons/22/216447/icon.png') no-repeat center left transparent;
padding-left:35px;
}
&#13;
答案 1 :(得分:0)
$(this).removeClass().addClass(this.options[this.selectedIndex].className);
答案 2 :(得分:0)
虽然你已经选择了答案,但我认为我提供了另一种选择,因为到目前为止所有的答案似乎都有些过于复杂。那就是说,我建议:
$('select').change(function () {
// setting the className of the changed <select> element
// to the className of the selected <option>
// (this.selectedIndex gives theindex of the selected
// <option> from among the options collection of the
// <select> element:
this.className = this.value;
});
$(document).ready(function($) {
$('select').change(function() {
this.className = this.options[this.selectedIndex].className;
});
});
&#13;
select {
border: 2px solid #000;
}
.wordpress {
border-color: red;
}
.joomla {
border-color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select class="wordpress">
<option value="1" class="wordpress">Hello</option>
<option value="2" class="joomla">2222</option>
<option value="3" class="wordpress">33333</option>
<option value="4" class="joomla">44444</option>
</select>
&#13;
外部JS Fiddle demo,用于实验。
参考文献: