我正在使用 jquery 移动自定义选择菜单来选择国家/地区。我想将按钮图标设置为国旗。
我有这个:
<div class="ui-select">
// select button
<a href="#" role="button" id="brandsByCountry-button" class="ui-btn ui-btn-up-c ui-btn-icon-right ui-btn-corner-all ui-shadow">
<span class="ui-btn-inner ui-btn-corner-all">
<span class="ui-btn-text">Germany</span>
// country flag icon - insert country class here
<span class="ui-icon ui-icon-lang ui-icon-shadow"></span>
</span>
</a>
// selectmenu
<select data-iconpos="right" class="ui-fake-icon" data-icon="lang" data-native-menu="false" id="brandsByCountry" name="brandsByCountry">
<option data-placeholder="true" value="default">Country</option>
<option value="be">Belgium</option>
<option value="ch">Switzerland</option>
<option value="de" selected="selected">Germany</option>
</select>
</div>
我可以通过从 val() 添加一个国家类到span.ui-icon来设置标志。
问题:
当用户更改选择时,我需要添加一个新类并删除旧的国家/地区类。我不知道如何在不删除所有其他必要类的情况下删除该类。此外,我很难使用 val() 添加相应的类。
我有这个:
$('#brands').bind( "pagebeforeshow", function( event, data ) {
var initBrand = $('#brandsByCountry').val(),
closestBtn = $('#brandsByCountry').prev('.ui-btn');
closestBtn.addClass( initBrand ); // doesn't work
closestBtn.addClass( "test" ); // works
$('#brandsByCountry').live('change', function() {
var str = $(this).children('option[selected]').val();
console.log(str); // ok, gets new class
closestBtn.addClass( str ).removeClass(':not(".ui-icon, .ui-icon-lang, .ui-icon-shadow")');
})
})
感谢您的意见!
这里的解决方案
是我基于天际回答的最终版本。我添加了对多项选择的检查以及要显示的选择的默认值。
$('#brands').one( "pagebeforeshow", function( event, data ) {
// initial class name
$('#brandsByCountry').data('oldVal', 'global' );
// designated element
var closestBtn = $('#brandsByCountry').prev('a'),
orginalClass = $('#brandsByCountry').data('oldVal');
// add inital class/icon
closestBtn.addClass( orginalClass+"");
$('#brandsByCountry').change(function() {
var $this = $(this),
// if more than one option is selected go back to global icon
newClass = $this.val().length >= 2 ? "global" : $this.val(),
oldClass = $this.data('oldVal');
$this.data('oldVal', newClass);
closestBtn.removeClass(oldClass+"").addClass(newClass+"");
});