开发者

Port small function from jQuery to Prototype?

开发者 https://www.devze.com 2023-02-04 04:00 出处:网络
For once I need to use Prototype instead of jQuery, which I\'m not very comfortable with. Can someone help me convert this following script:

For once I need to use Prototype instead of jQuery, which I'm not very comfortable with. Can someone help me convert this following script:

var output={};
$('ul li').each(function(i,v){
    var l=$(this).text().substring(0,1).toUpperCase();
    if(typeof(output[l])=="undefined") output[l]=[];
    output[l].push($(this).text());
});
$('ul').empty();
for(var i in output){
    $('ul').append('<li><p>'+i+'</p></li>');
    for(var j in output[i]){
        $('ul').append('<li>'+output[i][j]+'</li>');
    }
}

Full source: http://jsfidd开发者_开发技巧le.net/flxfxp/3LwH8/7/

Many thanks!


var output = $H({});

$$("ul li").each(function(el){
  var l = el.innerHTML.substr(0,1).toUpperCase();
  if(typeof(output.get(l))=="undefined") output.set(l, []);
  output.get(l).push(el.innerHTML);
})

$$('ul').invoke("update", '');

output.keys().each(function(key){
  var values = output.get(key);
  $$('ul').first().insert('<li><p>'+key+'</p></li>');
  values.each(function(v){
    $$('ul').first().insert('<li>'+v+'</li>');
  });
});

Tested with latest Prototype


My Prototype is a little rusty but:

var output = $$('ul li').reduce({}, function(rv, li) {
  var l = li.innerHTML.substring(0, 1).toUpperCase();
  (rv[l] = rv[l] || []).push(li.innerHTML);
  return rv;
});
$$('ul').update($(output).collect(function(list, letter) {
  return '<li><p>' + letter + '</p></li>' + list.collect(function(txt) {
    return '<li>' + txt + '</li>';
  }).join('');
}).join(''));

The only thing I'm worried about is that .innerHTML isn't the same as .text() in jQuery, but I don't know how to do .text() in Prototype.


    document.observe("dom:loaded", function () {
        var output = {};
        $$('ul.wikiext-taggedpages li').each(function(v, i) {
            var l = v.innerHTML.substring(0, 1).toUpperCase();
            if (typeof(output[l]) == "undefined") {
                output[l] = [];
            }
            output[l].push(v.innerHTML);
        });

        console.log('output', output);

        $$('ul.wikiext-taggedpages')[0].update('');
        for (var i in output) {
            if (output.hasOwnProperty(i)) {
                $$('ul.wikiext-taggedpages')[0].insert('<li><p>' + i + '</p></li>');
                for (var j in output[i]) {
                    if (output[i].hasOwnProperty(j)) {
                        $$('ul.wikiext-taggedpages')[0].insert('<li>' + output[i][j] + '</li>');
                    }
                }
            }
        }
    });
0

精彩评论

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