处理下拉列表中的键盘

时间:2010-12-13 21:55:06

标签: jquery

我正在根据单位(km到m,lb到g等)转换值。我有它工作,除了一个我似乎无法解决的错误。

这是处理事件的函数(转换发生在jQuery插件中):

function unitConversion() {
    var from;

    // Remember which unit was selected in the drop down list.
    $('select.unit').live('click', function () {
        from = $(this).find('option:selected').text();
    });

    // Now handle the conversion.
    $('select.unit').live('change', function () {
        // Get the from and to values.
        // var from = $(this).prev().find('option:selected').text();
        var to = $(this).find('option:selected').text();

        // Change the text for each field that corresponds with this component.
        var textBoxes = $(this).closest('div.data-group').find('input:text');
        textBoxes.each(function () {
            var curValue = $(this).val();
            $(this).val($(this).unitConvert({
                value: curValue,
                from: from,
                to: to
            }));
        });
    });
}

这很好用(但是,如果你对这段代码有任何改进,我总是想要学习)。但是,我遇到的最初问题是我必须记住下拉列表中之前选择的单元。因此,我正在做的“点击”事件。

只要个人使用鼠标,此解决方案效果很好。但是,如果我使用键盘选中下拉列表,并按向上/向下箭头键,则没有任何反应。我已经尝试了各种关键*事件,但这些事件似乎也没有用。我应该在这里做什么来处理键盘和鼠标输入?

(我希望更改事件允许我访问之前选择的项目,但似乎并非如此。)

更新:我想提供一些额外的说明。

如果我使用焦点事件,那么转换会变得有些奇怪。原因是因为我第一次获得焦点时只设置了“从”值。如果我希望每次都能正确进行转换,我必须不再关注下拉列表,然后执行该过程。不太有用。

此外,无论出于何种原因,当我选中该字段然后单击向上和向下箭头时,更改事件不会触发。我真的不知道为什么会这样......

3 个答案:

答案 0 :(得分:1)

我会对您的代码进行两处更改。

首先确保您的选项包含textvalue

<select>
   <option value="km">KM</option>
   ...
</select>

然后而不是做$('select.unit').find('option:selected').text();你可以写:

$('select.unit').val();

这也更正确,因为您可以向该值显示不同的文本,例如向用户显示“km”,但仍然具有与插件一起使用的值“km”。

现在,关于真正的问题......

“记住”以前状态的最简单方法是将数据附加到元素本身。在避免内存泄漏和各种其他问题的同时,最好的方法是使用jQuery的data()。只要给它一个名字和一个值,它就会在你选择的select元素上记住它。

// Now handle the conversion.
$('select.unit').live('change', function () {
    // Get the from and to values.
    var from = $(this).data("from");
    var to = $(this).val();

    // Remember the from value for next time
    $(this).data("from", to);

    // Change the text for each field that corresponds with this component.
    var textBoxes = $(this).closest('div.data-group').find('input:text');
    textBoxes.each(function () {
        var curValue = $(this).val();
        $(this).val($(this).unitConvert({
            value: curValue,
            from: from,
            to: to
        }));
    });
});

使用相同的方法设置文档加载的from值(如果需要):

$(function () {
   $('select.unit').each(function () {
      $(this).data("from", $(this).val());
   });
});

答案 1 :(得分:0)

您应该只注意click,而不是收听focus。这应该适用于鼠标和键盘。

答案 2 :(得分:0)

不需要其他事件..您可以添加名为_from的全局变量(在函数外部),使用文档就绪事件中的选定值对其进行初始化,然后将_from设置为等于{完成处理后{1}}。

这种方式to将始终保留以前选择的下拉列表值。

代码示例:

_from

测试用例:http://jsfiddle.net/TuHnB/