gpt4 book ai didi

javascript - 如何使用 JavaScript 从选项 DOM 元素中获取先前和新的选定值?

转载 作者:太空狗 更新时间:2023-10-29 13:08:32 25 4
gpt4 key购买 nike

当调用 onChange 或类似事件时,如何使用 JavaScript 检索新选择的值和先前选择的值?

<select size="1" id="x" onchange="doSomething()">
<option value="47">Value 47</option>
...


function doSomething() {
var oldValue = null; // how to get the old value?
var newValue = document.getElementById('x').selected.value;
// ...

谢谢! :)

最佳答案

直接使用 JavaScript 和 DOM,像这样 ( live example ):

var box, oldValue;

// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
// DOM2 standard
box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
// IE fallback
box.attachEvent("onchange", changeHandler);
}
else {
// DOM0 fallback
box.onchange = changeHandler;
}

// Our handler
function changeHandler(event) {
var index, newValue;

// Get the current index
index = this.selectedIndex;
if (index >= 0 && this.options.length > index) {
// Get the new value
newValue = this.options[index].value;
}

// **Your code here**: old value is `oldValue`, new value is `newValue`
// Note that `newValue`` may well be undefined
display("Old value: " + oldValue);
display("New value: " + newValue);

// When done processing the change, remember the old value
oldValue = newValue;
}

(我假设以上所有内容都在函数内部,如页面加载函数或类似函数,如 live example 中,因此我们不会创建不必要的全局符号 [box , oldValue, 'changeHandler`].)

请注意,change 事件由不同的浏览器在不同的时间引发。一些浏览器在选择更改时引发事件,其他浏览器等到焦点离开选择框。

但您可能会考虑使用像 jQuery 这样的库, Prototype , YUI , Closure , 或 any of several others ,因为它们使很多这样的东西变得容易得多。

关于javascript - 如何使用 JavaScript 从选项 DOM 元素中获取先前和新的选定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4315727/

25 4 0