从select中选择以前选项中的数据以及当前选项中的数据

时间:2014-12-16 23:54:16

标签: javascript jquery scope

所以我知道JavaScript中的范围可能有点不稳定我已经尝试了一些不同的东西,包括将变量声明附加到窗口(即window.var)并在内部和外部声明变量功能但无济于事。这就是我所拥有的:

$(".some_field").on('focus', function () {

    // Store the previous option value before the change
    prev = String($(":selected", $(this)).data('option_id'));

}).change( function() {

    alert(prev); // alerts '4'

    current = String($(":selected", $(this)).data('option_id'));
    alert(current) // alerts '5'

    alert(prev); // alerts '5' ..... it should alert '4'
});    

基本上在更改功能中,我需要使用前一个和当前选项ID

进行操作

3 个答案:

答案 0 :(得分:2)

我建议使用旧的值数据属性来修饰输入,而不是使用全局。

试试这个:http://jsfiddle.net/zpe7azsq/16/

例如:

$(".some_field").on('focus', function () {
    $(this).data('oldValue', $(this).data('option_id'));
}).change(function () {
    alert("Old value on focus was: " + $(this).data('oldValue'));
    alert("Current option_id value: "+$(this).data('option_id'));
});

答案 1 :(得分:1)

您需要使用一个变量/属性来存储前一个值每个元素。全局变量无济于事。实际上你甚至不需要那些focus事件。

$(".some_field").each(function () {
     $(this).data('id_value', $(":selected", this).data('option_id'));
}).change(function(e) {
     var previous = $(this).data('id_value'),
         current = $(":selected", this).data('option_id');

     alert(…); // or whatever

     $(this).data('id_value', current);
});

答案 2 :(得分:0)

以@Scott的回答作为指导,最终为我工作的是什么。我使用父元素来存储数据...... @ Bergi的答案也适用!

$(".some_field").on('focus', function () {
    // Store the previous option value before the change
    $(this).parent().data('prev_option_id', $(":selected", $(this)).data('option_id'));
}).change( function() {
    current = String($(":selected", $(this)).data('option_id'));
    alert("Old value on focus was: " + $(this).parent().data('prev_option_id'));
    alert("Current option_id value: "+current);
});