1

如何从<select>原型中获取先前选择的选项,以便在脚本中出现任何故障时“回滚”选择?

4

1 回答 1

0

您不能直接使用原型执行此操作,但这是一个处理“可回滚”选择的类:

var UndoableSelect = Class.create({
    _$select: null,
    _selectedValue : null,
    _lastSelectedValue: null,
    initialize: function(elementOrId)
    {
        this._$select = $(elementOrId);
        this._lastSelectedIndex = this._$select.selectedIndex;
        this._selectedIndex = this._lastSelectedIndex;
        this._$select.observe('change', this._changeHandler.bind(this));
    },
    undoLastSelection: function()
    {
        this._$select.selectedIndex = this._lastSlectedIndex;
        this._selectedIndex = this._lastSelectedIndex;
    },
    _changeHandler: function(event)
    {
        this._lastSelectedIndex = this._selectedIndex;
        this._selectedIndex = this._$select.selectIndex;
    }
});

你可以这样使用:

// this one line under has to be called only once per page load (where there is the select of course):
var theSelect = new UndoableSelect('id_of_the_select');
$('id_of_the_select').observe('change', function(event)
{
    // your code, if you need to rollback, do this:
    theSelect.undoSelection();
});

抱歉没有太多解释,但我现在没有太多时间。我只是在没有测试的情况下编写了代码,所以如果有任何问题让我知道,我会花更多时间来修复它;-)

于 2012-08-16T16:17:48.727 回答