如何使用JavaScript从选项DOM元素中获取上一个和新选择的值?

Tho*_*ler 10 html javascript xhtml

当调用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;
  // ...
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

T.J*_*der 9

使用直接的JavaScript和DOM,像这样(实例):

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;
}
Run Code Online (Sandbox Code Playgroud)

(我假设所有的上面是一个函数里,像一个页面加载函数或类似的,如活生生的例子,所以我们不会造成不必要的全局符号[ box,oldValue"changeHandler`.)

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

但是你可能会考虑使用像jQuery,Prototype,YUI,Closure其他几个库这样的库,因为它们使这些东西变得更容易.


小智 5

看看这里:在改变之前获得选择(下拉)的价值 我认为更好,

(function () {
    var previous;

    $("select").focus(function () {
        // Store the current value on focus, before it changes
        previous = this.value;
    }).change(function() {
        // Do something with the previous value after the change
        alert(previous);
    });
})();
Run Code Online (Sandbox Code Playgroud)