我想要实现的事情是,每当<select>下拉菜单被更改时,我想要更改前的下拉菜单的值。我使用1.3.2版本的jQuery和使用的变化事件,但我在那里得到的值是变化后。

<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>

让我们说当前选项My现在被选中,当我在onchange事件中将其更改为堆栈时(即当我将其更改为堆栈时),我想要它之前的值,即在这种情况下我的期望。

如何实现这一目标?

编辑:在我的情况下,我有多个选择框在同一页,并希望同样的事情被应用到所有他们。也所有我的选择后插入页面加载通过ajax。


当前回答

我选择Avi Pinto的解决方案,它使用jquery.data()

使用焦点并不是一个有效的解决方案。它在你第一次改变选项时起作用,但如果你停留在选择元素上,并按“上”或“下”键。它不会再次通过焦点事件。

所以解应该是这样的,

//set the pre data, usually needed after you initialize the select element
$('mySelect').data('pre', $(this).val());

$('mySelect').change(function(e){
    var before_change = $(this).data('pre');//get the pre data
    //Do your work here
    $(this).data('pre', $(this).val());//update the pre data
})

其他回答

手动跟踪值。

var selects = jQuery("select.track_me");

selects.each(function (i, element) {
  var select = jQuery(element);
  var previousValue = select.val();
  select.bind("change", function () {
    var currentValue = select.val();

    // Use currentValue and previousValue
    // ...

    previousValue = currentValue;
  });
});

我使用事件“live”,我的解决方案基本上类似于Dimitiar,但不是使用“焦点”,我以前的值被存储时,“点击”被触发。

var previous = "initial prev value";
$("select").live('click', function () {
        //update previous value
        previous = $(this).val();
    }).change(function() {
        alert(previous); //I have previous value 
    });

我选择Avi Pinto的解决方案,它使用jquery.data()

使用焦点并不是一个有效的解决方案。它在你第一次改变选项时起作用,但如果你停留在选择元素上,并按“上”或“下”键。它不会再次通过焦点事件。

所以解应该是这样的,

//set the pre data, usually needed after you initialize the select element
$('mySelect').data('pre', $(this).val());

$('mySelect').change(function(e){
    var before_change = $(this).data('pre');//get the pre data
    //Do your work here
    $(this).data('pre', $(this).val());//update the pre data
})

我想为解决这个问题贡献另一种选择;因为上面提出的解决方案并没有解决我的情况。

(function()
    {
      // Initialize the previous-attribute
      var selects = $('select');
      selects.data('previous', selects.val());

      // Listen on the body for changes to selects
      $('body').on('change', 'select',
        function()
        {
          $(this).data('previous', $(this).val());
        }
      );
    }
)();

这确实使用了jQuery,所以def.在这里是一个依赖项,但这可以在纯javascript中进行调整。(在body中添加监听器,检查原始目标是否为select, execute函数,…)

通过将更改侦听器附加到主体,您几乎可以确定它将在特定的侦听器之后触发选择,否则'data-previous'的值将在您甚至可以读取它之前被覆盖。

当然,这是假设您更喜欢为set-previous和check-value使用单独的侦听器。它正好符合单一责任模式。

注意:这将把“先前”功能添加到所有选择中,所以如果需要,请确保对选择器进行微调。

有几种方法可以达到你想要的结果,以下是我的拙见:

让元素保持之前的值,因此添加属性'previousValue'。

<select id="mySelect" previousValue=""></select>

初始化后,'previousValue'现在可以用作属性。在JS中,要访问这个select的previousValue:

$("#mySelect").change(function() {console.log($(this).attr('previousValue'));.....; $(this).attr('previousValue', this.value);}

使用'previousValue'后,将属性更新为当前值。