下拉currentIndex onchange [英] Dropdown currentIndex onchange
问题描述
在JS函数,我可以很容易地检查用户使用 selectedIndex 属性选择的选项的索引。但是,我也想知道用户将其改为的原始值是什么。
是否有一个属性持续
基本上是原始值,即
选项2在这种情况下。
就像我把一个概念放在一起 - 可能有更好的方法来做这:
var vals = [];
document.getElementById(colors)。onchange = function(){
vals.unshift(this.selectedIndex);
};
函数getPrevious(){
alert(vals [1]); //你会在这里需要更多的逻辑
//这是有目的的简单化
}
-
< select id =colors>
< option> Red< / option>
< option>绿色< /选项>
< option>蓝色< /选项>
< / select>
封闭示例:
I我们试图将这一切都与实际的下拉元素结合起来。诚实地说,这是我第一次为下拉本身添加功能,所以我不能保证这不会造成任何后果:
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(); }
//设置初始状态
colors.setPrevious();
there is a dropdown with 5 options. Currently,option 2 is selected.The user selects option 4 now.The onchange event gets fired which is caught in a JS function listening for onchange on the select.
In the JS function, I can check easily the index of the option selected by the user using the selectedIndex property.However, I want to also know what was the original value that the user changed it from.
Is there a property that persists basically the original value i.e. option 2 in this case.
Just as a concept I put together the following - there may very well be a better way to do this:
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>
Closed-up Example:
I've tried to tie this all into the actual drop-down element itself. In all honesty, this is the first time I've ever add functions to the dropdown itself, so I cannot promise that this won't have consequences:
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();
这篇关于下拉currentIndex onchange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!