我正在尝试编写一个脚本,允许按钮单击以更改select元素中的选定选项。这个脚本在Chrome中有效,但在Firefox中却没有,为什么会这样?
http://jsfiddle.net/orjan/hsvp7pt8/
var searchOption = $('.container .select-box option:selected').text();
var searchValue = $('.container .select-box option:selected').val();
$('.container').each(function () {
$(this).children('.select-box').attr('value', searchValue);
if ($(this).find('.select-box option:selected').val() == 'articles') {
$(this).toggleClass('active');
}
});
$('.container .select-label').click(function () {
$(this).parent().toggleClass('active');
if ($(this).siblings('.select-box').children('option:selected').val() == 'option-a') {
$(this).siblings('.select-box').children('option:selected').removeAttr('selected');
$(this).siblings('.select-box').children('option[value="option-b"]').attr('selected', 'selected');
var searchValue = $('.container .select-box option:selected').val();
} else {
$(this).siblings('.select-box').children('option:selected').removeAttr('selected');
$(this).siblings('.select-box').children('option[value="option-a"]').attr('selected', 'selected');
var searchValue = $('.container .select-box option:selected').val();
}
$(this).siblings('.select-box').attr('value', searchValue);
});
答案 0 :(得分:0)
您不应使用.attr('selected')
更改菜单的值。只需使用$('.select-box').val('new-value')
直接设置菜单的值。
var searchOption = $('.container .select-box option:selected').text();
var searchValue = $('.container .select-box').val();
$('.container').each(function () {
$(this).children('.select-box').attr('value', searchValue);
if ($(this).find('.select-box option:selected').val() == 'articles') {
$(this).toggleClass('active');
}
});
$('.container .select-label').click(function () {
$(this).parent().toggleClass('active');
var select = $(this).siblings('.select-box');
if (select.val() == 'option-a') {
select.val('option-b');
} else {
select.val('option-a');
}
});
.active {
background-color: red;
}
.container {
padding: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="select-label">Change</button>
<select class="select-box">
<option value="option-a" selected="selected">Example A</option>
<option value="option-b">Example B</option>
</select>
</div>