当从html选择处理“更改”事件时,我想获得最后选择的值/索引。
对于前。
$('#mySelect').live('change', function(event){
var idx = $(this).prop('selectedIndex');
});
idx在更改事件触发器后保留值。我需要在事件触发之前选择的值。
答案 0 :(得分: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);
});
答案 1 :(得分: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;
});
答案 2 :(得分:0)
您可以使用事件处理函数之外的变量范围跟踪值,如下所示:
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
});
答案 3 :(得分:0)
你可以尝试这样的事情 -
var lastSeelctedlist = "";
$('#mySelect').live('change', function(event){
lastSeelctedlist = $(this).val();
// you rest of code
});
答案 4 :(得分: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
}
此函数参数是select tag id,return对象包含3个属性 价值,文字,索引
在onchange事件上调用它
onchange = "getLastSelected(this)"
问候