2011-11-22 61 views
0

從html選擇處理「更改」事件時,我想獲取最後選擇的值/索引。在更改事件之前獲取html select的值

例如,

$('#mySelect').live('change', function(event){ 
     var idx = $(this).prop('selectedIndex'); 
}); 

idx保留更改後的值事件觸發器。我需要事件觸發前選擇的值。

回答

1

嘗試是這樣的,如果你有多個選擇:

var select = $('#mySelect'); 
select 
    .data("lastIndex", select[0].selectedIndex) 
    .live('change', function(event){ 
     var idx = this.selectedIndex; 
     var prevIdx = $(this).data("lastIndex"); 

     // Alert prev and new index 
     alert(prevIds + " - " + idx); 

     // Alert prev value and new value 
     alert($(this).find("option").eq(prevIdx) + " - " + $(this).find("option").eq(idx)); 

     // Set new index as old index 
     $(this).data("lastIndex", idx); 
    }); 
+0

這是一個很好的解決方案,因爲我沒有控制在我的頁面中存在多少選擇,使得使用多個變量不是一個合適的解決方案。 –

0

我會保存以前的值在不同的變量和手動更新

// what is the value when <select> was just loaded? 
var previous_value = $('#mySelect').prop('selectedIndex'); 

$('#mySelect').live('change', function(event){ 
     var idx = $(this).prop('selectedIndex'); 
     // at this point previous_value has the previous value and idx - current 
     // ... do something here ... 
     // updating previous_value for the next time 
     previous_value = idx; 
}); 
0

您可以使用vairable作用域的事件處理函數的外部保持價值的軌道,就像這樣:

var mySelect = $('#mySelect'), 
    previousValue = mySelect.val(); 

mySelect.live('change', function() { 

    alert(mySelect.val()); // alerts current value 
    alert(previousValue); // alerts previous value 

    previousValue = mySelect.val(); // save so it can be referenced next time 

}); 
0

可以你可以試試這個 -

var lastSeelctedlist = ""; 
$('#mySelect').live('change', function(event){ 
     lastSeelctedlist = $(this).val(); 
// you rest of code 
}); 
0

如果我得到你的權利那麼這裏是純JavaScript的解決方案

function getLastSelected(e) 
    { 
    var s = e; 
    var optionsSelected = []; 
    for(var i =0;i<s.options.length;i++) 
    { 
    if(s.options[i].selected == true) 
     { 
     optionsSelected[optionsSelected.length] = {Value : s.options[i].value,Text:s.options[i].text,Index : i}; 
     } 
    } 

    var lastSelected =((optionsSelected.length >0)?(optionsSelected[optionsSelected.length - 1]):(null)) ; 
    return lastSelected; // or do what you have to do here 
//put it in custom attribute or what ever 
    } 

這個函數的參數是選擇標籤ID和返回的對象是包含3個屬性 值,文本,指數

調用它onchange事件

onchange = "getLastSelected(this)" 

Regards

相關問題