在选择中从上一个选项获取数据,从当前选项获取数据

Get data from previous option in a select as well as data from current option

本文关键字:获取 数据 选项 选择 上一个      更新时间:2023-09-26

所以我知道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 进行操作

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

试试这个: 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'));
});

您需要使用一个变量/属性来存储每个元素的先前值。全局变量无济于事。实际上,您甚至不需要这些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);
});

以@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);
});