开发者

Converting jQuery each function to Prototype.js

I am trying to convert a section of code from jQuery to prototype.js and need some assistance.

Prototype.js

$$('select').invoke('observe', 'change', function() {
    var sel = $(this);
    var selval = $(this).getValue();
    $(this).select('option').each(function (e) {
        $(e).remove();
        if ($(e).getValue() == selval) {
                 $(sel).append('<o开发者_StackOverflow中文版ption value="'+$(e).getValue()+'" selected="selected">'+$(e).text+'</option>');
        } else {
            $(sel).append('<option value="'+$(e).getValue()+'">'+$(e).text+'</option>');
        }
    });
});

jQuery

$('select').change(function() {
    var sel = $(this);
    var selval = $(this).val();
    $(this).find('option').each(function () {
        $(this).remove();
        if ($(this).val() == selval) {
            $(sel).append('<option value="'+$(this).val()+'" selected="selected">'+$(this).text()+'</option>');
        } else {
            $(sel).append('<option value="'+$(this).val()+'">'+$(this).text()+'</option>');
        }
    });
});

The first part of the select seems to work, but the each part doesn't in the prototype version. It doesn't like getValue(), etc. Says $(e).getValue is not a function. How do I get the each command to run and retrieve the element value?

Any help would be appreciated.

Thanks.


Working Code:

document.observe('dom:loaded',function(){
    $$('select').invoke('observe', 'change', function() {
        var sel = $(this);
        var selval = $(this).getValue();

        $(this).select('option').each(function (e) {
            $(e).remove();
            if ($(e).value == selval) {
                $(sel).insert('<option value="'+$(e).value+'" selected="selected">'+$(e).text+'</option>');
            } else {
                $(sel).insert('<option value="'+$(e).value+'">'+$(e).text+'</option>');
            }
        });
    });
});


So you loop through all options and delete them just so you can replace them with the selected attribute? That sounds like a hard way to do this:

$$('select').invoke('observe', 'change', function() {
    this.select('option').invoke('writeAttribute', 'selected', false);
    this.select('option[value='+$F(this)+']').invoke('writeAttribute', 'selected');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜