4

我在 iPad 上选择和取消选择选项时遇到问题。

"Shop by Color" is an option without value, so when this option is selected it will display all items. When any other option is selected it will display items in that category.

我想要的是:

  • 当您单击 .othervalue 选项时,应取消选择“按颜色购物”(.firstvalue),并应选择单击的选项
  • 当您单击 .firstvalue 选项时,它应该被选中,并且所有其他选项 (.othervalue) 应该被取消选择

这是我尝试过的:

$(document).ready(function() {
    $('select').change(function() {
        var $this = $(this);
        if($("option.firstvalue").is(":selected")) {                
            $this.find('option:first').attr('selected', false);
        } else {                               
            $this.find('option:gt(0)').attr('selected', false);
        }
    });
});

** 完整代码在:http: //jsfiddle.net/GNpzq/ **

我认为我应该使用 $('select').change() 因为 iPad 正确触发了该事件,但我不确定。

有人可以帮我处理这段代码吗?

谢谢!

编辑:这是解决问题的代码,也许有人会使用。

$(function() {
    // select and deselect default OPTION for filters
    var firstSelectState = new Array;
    var optionsArray = new Array;

    $('select').change(function() {
        var id = this.id;
        if (!id) {
            id = Math.round(Math.random()*99999);
            this.id = id;
        }
        if (typeof(firstSelectState[id])=="undefined") firstSelectState[id] = this.options[0].selected;
        var tmpOptionsArray = new Array();
        for (var i = 1; i<this.options.length; i++) {
            tmpOptionsArray[i] = this.options[i].selected;
        }

        if (typeof(optionsArray[id])=="undefined") {
            optionsArray[id] = tmpOptionsArray;
        }

        var firstSelected = (firstSelectState[id]!=this.options[0].selected);
        var otherSelected = false;
        for (var i = 1; i<this.options.length; i++) {
            if (optionsArray[id][i]!=tmpOptionsArray[i]) {
                otherSelected = true;
                break;
            }
        }

        optionsArray[id] = tmpOptionsArray;
        if (firstSelected && !otherSelected) {
            for (var i = 1; i<this.options.length; i++) {
                this.options[i].selected = false;
            }
        } else {
            this.options[0].selected = false;
            firstSelectState[id] = false;
        }


    });
});
4

1 回答 1

1

目前您正在阻止任何选择,您的条件说如果选择了第一个选项取消选择它,如果选择了其他选项也取消选择它们,请尝试以下操作:

$('select').change(function() {
    if (this.selectedIndex === 0) {
        $('option:gt(0)', this).prop('selected', false);
    } else {
        $('option:first', this).prop('selected', false);
    }
});

http://jsfiddle.net/LynCV/

于 2012-11-01T17:46:59.533 回答