开发者

Jquery to Prototype

开发者 https://www.devze.com 2023-03-05 07:56 出处:网络
How do I convert the jquery code below to prototype? <script> $(document).ready (function() { $(\"#valor\").keyup(function(){

How do I convert the jquery code below to prototype?

<script> 
    $(document).ready (function() {
        $("#valor").keyup(function(){
            var resultVal = 0.0;
            var objR开发者_如何学运维egExp = '\s+';
            $("#valor").each ( function() {
                resultVal += parseFloat ( $j(this).val().replace(/\s/g,'').replace(',','.'));
            });
            $("#total").val(resultVal);  
        });
    });
</script>

Thanks.


I don't know, but pure JavaScript is always nice:

function doLoad() {
     var valor = document.getElementById("valor");
     valor.onkeyup = function() {
          var resultVal = 0.0;
          var objRegExp = '\s+';
          for(var i = 0; i < valor.childNodes.length; i++) {
               var n = valor.childNodes[i];
               if(n.nodeType === 1) resultVal += parseFloat(n.value.replace(/\s/g, '').replace(',', '.'));
          }
          document.getElementById("total").value = resultVal.toString();
     };
}

if(window.addEventListener)
     window.addEventListener("load", doLoad, false);
else
     window.attachEvent("onload", doLoad);


Here's a working example with the migration:

http://jsfiddle.net/MaQA5/

Code:

eventObserver = function() {
    var resultVal = 0.0;
    var objRegExp = '\s+';
    $$(".valor").each(function(el) {
        resultVal += parseFloat($(el).getValue().replace(/\s/g, '').replace(',', '.'));
    });
    $("total").setValue(resultVal);
};

$$('.valor').each(function(el) {
    el.observe('keyup', eventObserver);
});

Some comments:

From your code, I supposed you have several inputs with the same id (valor). If this is the case, that's wrong, as ids must be unique in the whole DOM.

That's why I changed that for a class named valor.

Prototype has a special $$ function to get elements by css-selector. But uses $ for id search or to turn a DOM element into a Prototype-empowered element.

When calling to each method, instead of using this as every element in the original collection (like you do in jQuery), you must use the first argument in the function: el.

Instead of calling the keyup jQuery method, you must use observe('keyup', ....

In my opinion, jQuery is more elegant, or at least, the Prototype that I know is not that fancy :)

0

精彩评论

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

关注公众号