2013-06-27 68 views
0

我使用的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之前存儲來自所有選擇的值?

+1

它沒有。它只存儲一個值。如果您[學習如何**調試** JavaScript](http://www.netmagazine.com/tutorials/javascript-debugging-beginners),則可以設置斷點並自行檢查變量。 –

回答

1

當您專注於任何選擇,previous獲取選擇值。當您更改, $(this).val()得到改變的值,並previous contans以前的值(進行了更改前的一個。

所以,基本上你的函數的作用是什麼,只要你選擇任何選項,它禁用在其他兩個selects

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

這條線是指選擇,選擇所有select除對於當前一個,並且所述disableoptionthis.val()

,然後將它類似地使previous選項,因爲沒有被選擇了

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

選擇所有selects除了this和與所選擇的值除去的所有optionsdisable