有一个包含 5 个选项的下拉菜单。当前,选项 2 被选中。用户现在选择选项 4。onchange 事件被触发,该事件被 JS 函数捕获,该函数在选择时监听 onchange。
在 JS 函数中,我可以使用 selectedIndex 属性轻松检查用户选择的选项的索引。但是,我还想知道用户更改它的原始值是多少从。
Is there a property that persists basically the original value i.e. option 2 in this case.
最佳答案
作为一个概念,我将以下内容放在一起 - 很可能有更好的方法来做到这一点:
var vals = [];
document.getElementById("colors").onchange = function(){
vals.unshift(this.selectedIndex);
};
function getPrevious(){
alert(vals[1]); // you'll need more logic here
// this is purposefully simplistic
}
--
<select id="colors">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
封闭示例:
我试图将这一切与实际的下拉元素本身联系起来。老实说,这是我第一次向下拉列表本身添加功能,所以我不能保证这不会产生任何后果:
var colors = document.getElementById("colors");
colors.vals = [];
colors.setPrevious = function() { this.vals.unshift(this.selectedIndex); }
colors.getPrevious = function() { return this.vals[1]; }
colors.onchange = function() { this.setPrevious(); this.getPrevious(); }
// set initial state
colors.setPrevious();
关于javascript - 下拉 currentIndex onchange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1983535/