2

我真的是 Web 开发的新手,我正在尝试使用 Javascript 更改一些输入的文本。这是我的代码必须执行的示例

<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace "R$" with "" in the field below:</p>

<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var x=document.getElementByTagName("input")

for(var i = 0; i < x.length; i++) {

  var str=x[i].innerHTML; 

  var n=str.replace(",",".");
  var n1 = n.replace("R$ ","");

  document.getElementById("demo").innerHTML=n1;
 }


}
</script>

</body>
</html>

所以,我想撤回“R$”并将“,”替换为“。” 对于一些数学运算。我必须对代码中的所有输入执行此操作。

4

4 回答 4

1

你快到了,替换了一些东西让它看起来像这样:

function myFunction() {
    var x = document.getElementsByTagName("input"); // ; was missing and you used getElementByTagName instead of getElementsByTagName

    for (var i = 0; i < x.length; i++) {

        var str = x[i].value; // use .value

        var n = str.replace(",", ".");
        var n1 = n.replace("R$ ", "");

        //document.getElementById("demo").innerHTML=n1; // use x[i] again instead
        x[i].value = n1; // and again use .value
    }
}

演示- 运行更新的代码


于 2013-04-11T12:15:54.713 回答
0

这些是所需的步骤 - 至少是第 1 步到第 3 步

  1. 将脚本移动到它所属的头部
  2. 将 getElementByTagName 更改为 getElementsByTagName,复数
  3. 获取和更改 x[i].value
  4. 链接替换

演示

<!DOCTYPE html>
<html>
<head>
<title>Replace example</title>
<script>
function myFunction() {
  var x=document.getElementsByTagName("input"); // plural

  for(var i = 0; i < x.length; i++) {
    var str=x[i].value; 
    x[i].value=str.replace(",",".").replace("R$ ","");
  }
 }
</script>
</head>

<body>

<p>Click the button to replace "R$" with "" in the field below:</p>

<input id="demo" value="R$ 1223,43"></input>
<input id="demo1" value="R$ 134523,67"></input>
<input id="demo2" value="R$ 12453,41"></input>

<button onclick="myFunction()">Try it</button>


</body>
</html>
于 2013-04-11T12:15:36.957 回答
0

首先,使用 .value 而不是 .innerHTML。.innerHTML 指的是标签打开和关闭内的文本。

其次,更正 var x=document.getElementByTagName("input") 的拼写,它应该是 getElementsByTagName

于 2013-04-11T12:16:11.987 回答
0

这个函数应该做你想做的:

function myFunction()
{
    var eles=document.getElementsByTagName("input");

    for(var i = 0; i < eles.length; i++) 
    {
        if(eles[i].type != 'text') continue; // inputs that aren't of type text dont make sense here
        var str = eles[i].value; 
        str=str.replace(",",".");
        str=str.replace("R$ ","");
        eles[i].value=str;
    }
}
于 2013-04-11T12:17:11.763 回答