我想要实现的事情是,每当<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。


当前回答

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

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

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

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

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

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

其他回答

最好的解决办法:

$('select').on('selectric-before-change', function (event, element, selectric) {
    var current = element.state.currValue; // index of current value before select a new one
    var selected = element.state.selectedIdx; // index of value that will be selected

    // choose what you need
    console.log(element.items[current].value);
    console.log(element.items[current].text);
    console.log(element.items[current].slug);
});

我需要根据选择显示一个不同的div

这就是如何使用jquery和es6语法来做到这一点

HTML

<select class="reveal">
    <option disabled selected value>Select option</option>
    <option value="value1" data-target="#target-1" >Option 1</option>
    <option value="value2" data-target="#target-2" >Option 2</option>
</select>
<div id="target-1" style="display: none">
    option 1
</div>
<div id="target-2" style="display: none">
    option 2
</div>

JS

$('select.reveal').each((i, element)=>{
    //create reference variable 
    let $option = $('option:selected', element)
    $(element).on('change', event => {
        //get the current select element
        let selector = event.currentTarget
        //hide previously selected target
        if(typeof $option.data('target') !== 'undefined'){
            $($option.data('target')).hide()
        }
        //set new target id
        $option = $('option:selected', selector)
        //show new target
        if(typeof $option.data('target') !== 'undefined'){
            $($option.data('target')).show()
        }
    })
})

那么,为什么不存储当前选定的值,而当选定的项被更改时,您将存储旧的值呢?(你可以根据自己的意愿再次更新)

在编写下拉“on change”动作函数之前,将当前选中的jquery下拉值保存在全局变量中。 如果你想在函数中设置之前的值,你可以使用全局变量。

//global variable
var previousValue=$("#dropDownList").val();
$("#dropDownList").change(function () {
BootstrapDialog.confirm(' Are you sure you want to continue?',
  function (result) {
  if (result) {
     return true;
  } else {
      $("#dropDownList").val(previousValue).trigger('chosen:updated');  
     return false;
         }
  });
});

将它存储在一个self属性中(在文档就绪时):

$('#myselect').attr('orig',$('#myselect').val());

然后与变化后的值进行比较:

if ($('#myselect').attr('orig')!=$('#myselect').val()) ...