2017-03-15 41 views
-1

我有一个函数可以从输入字段中获取数字,数字在逗号而不是小数点上的点(123,5),所以我所做的就是将它们与替换进行转换以使计算,然后再更换他们逗号来显示结果,但它给我的问题,在过去的更换,这是一个Ajax回报Ajax将数字点替换为逗号不起作用

错误:"ncaught TypeError: subt1.replace is not a function at XMLHttpRequest.ajax.onreadystatechange"

我得到的计算正确的,但是当我尝试将其转换为逗号小数不起作用 我起因是因为打字,但我没弄错它

继承人我的代码

function updateCarrito(id,precio,moneda) { 

    var cant=document.getElementsByName("carrito_cantidad_"+id)[0].value; 

    var ajax=nuevoAjax(); 

    var contenedor=parent.document.getElementById('iconCarrito'); 

    var subt1=document.getElementById('cantidad_compra1_'+id).value; 

    if (moneda==1){ 
     var tot=document.getElementById('total_compra_pesos').value; 
    }else{ 
     var tot=document.getElementById('total_compra_dolares').value; 
    } 

    subt1 = subt1.replace(/\./g, '').replace(',', '.'); 
    tot = tot.replace(/\./g, '').replace(',', '.'); 

    ajax.open("GET", "http://www.somestuff.com?req=updateCarrito&id="+id+"&cant="+cant+"&precio="+precio,true); 
    ajax.onreadystatechange=function() { 

     if (ajax.readyState==4) { 
      contenedor.innerHTML = ajax.responseText; 

       tot=(tot-subt1); 
       subt1=(precio*cant); 
       subt1 = subt1.replace('.', ','); 

       document.getElementById('cantidad_compra1_'+id).value=subt1; 

       tot=(tot+subt1); 
       tot = tot.replace('.', ','); 

       if (moneda==1){ 
        document.getElementById('total_compra_pesos').value=tot; 
        document.getElementById('total_compra_pesos2').value=tot; 
       }else{ 
        document.getElementById('total_compra_dolares').value=tot; 
        document.getElementById('total_compra_dolares2').value=tot; 
       } 

     } 
    }; 

    ajax.send(null); 

} 
+0

你改写'subt1'的'值的任何一个后如预期器SUBT1 =(PRECIO *斜面);'。我认为它不再是一个字符串,现在它是一个数字。 '.replace'方法仅适用于字符串。 – surajck

+0

是的,你是对的,但我无法弄清楚如何转换它来改变,我使用numComma =(subt1.toString())。replace(“。”,“,”);现在和测试它,似乎工作... – Davyt

回答

1

这里有一个数字转换为字符串的几种方法:

subt1 = String(precio*cant) 
subt1 = (precio*cant).toString() 
subt1 = (precio*cant) + '' 

subt1.replace将努力使用这些方法

1

看起来你调用替换上一批而不是一个字符串。 subt1=(precio*cant);会将字符串的类型更改为数字。

您需要在调用replace之前施放。

subt1 = subt1.toString().replace('.', ','); 

编辑:看起来像我被殴打的评论。