如何从原型中的<select>
获取先前选择的选项,以便在脚本中的任何内容失败时我可以“回滚”选择?
答案 0 :(得分:0)
你不能直接用prototype做这个,但是这里有一个处理“rollbackable”选择的类:
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();
});
抱歉没有那么多解释,但我现在没有太多时间。我只是在没有测试的情况下编写代码,所以如果有任何问题让我知道,我会用更多的时间来修复它; - )