【问题标题】:Disabling select option禁用选择选项
【发布时间】:2013-06-27 18:29:59
【问题描述】:

我使用的 jQuery 函数禁止在一页上选择相同的选择值。例如:如果我在第 2 页有不同的选择,并且第一次选择时选择的值为 1,那么在第二次选择时,值 1 应该被禁用。我找到了注释的 jQuery 函数,但我不知道它的运行方式。

var previous = -1;
// Setting a previously selected value
$("select").change(function () {
// When any select element is changed
if ($(this).val() > -1) {
// When value is > -1
    // Get all selects but not the current one which triggered the change event
    $("select").not(this)
       .find("option[value=" + $(this).val() + "]").attr('disabled', 'disabled');
    // set the current option value to disabled

     // Get all selects but not the current one which triggered the change event
    $("select").not(this)
        .find("option[value=" + previous + "]").removeAttr('disabled');
    // Remove the disabled property on previous value
} else {
    // Get all selects but not the current one which triggered the change event
    $("select").not(this)
        .find("option[value=" + previous + "]").removeAttr('disabled');
    // Remove the disabled property
}
}).focus(function () {
previous = $(this).val();
// store the current value of the select to previous 
}); 

这里是 JSFiddle 链接:http://jsfiddle.net/Z2yaG/4/

有人可以解释一下 var 以前的数组吗?函数如何将所有选择的值存储在 var previous 上?

【问题讨论】:

标签: jquery


【解决方案1】:

当您关注任何选择时,previous 获取选择值。当你改变时, $(this).val() 获取更改后的值,previous 包含之前的值(更改前的值。

所以,基本上你的函数所做的是,一旦你选择任何选项,它就会在其他两个 selects 中禁用该选项

$("select").not(this) .find("option[value=" + $(this).val() + "]").attr('disabled', 'disabled');

这一行的意思是,选择除当前select之外的所有disableoption,其值为this.val()

然后它同样启用previous 选项,因为它不再被选中

$("select").not(this) .find("option[value=" + previous + "]").removeAttr('disabled');

选择除this 之外的所有selects 并删除具有所选值的所有options 中的disable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2012-07-22
    • 2016-10-06
    相关资源
    最近更新 更多