javascript - 如何让数组在 JavaScript 中工作?

标签 javascript arrays

我正在尝试使用 javascript 减少或增加文本框中的值。 当不使用任何数组时,我让它工作了。 如果您问为什么我需要在这个上使用数组。这是因为我稍后需要将它集成到一个更大的项目中,该项目非常需要数组。我是 javascript 的初学者,所以我真的不知道使用数组时需要什么条件才能完成这项工作。

<html>
<head>
  <script type="text/javascript">
    function blabla(){
        var a= document.x.qty[].value;
        var b=document.x.qty2[].value;
        var pa=parseInt(a);
        var plusqty= pa + 1;
        var txt = plusqty;
        var tbox = document.getElementById('qty');
        if (tbox)
        {
            tbox.value = txt;
        }

    }

    function lastog(){
        var a= document.x.qty.value;
        var b=document.x.qty2.value;
        var pa=parseInt(a);
        var plusqty= pa - 1;
        var txt = plusqty;
        var tbox = document.getElementById('qty');
        if (tbox)
        {
            tbox.value = txt;
        }
    }
  </script>
</head>

<body>
  <form name="x">
    number 1<input type="text" id="qty" name="qty[]" value=""><br/>
    number 2<input type="text" id="qty2" name="qty2" value=""><br/>
    number 3<input type="text" id="qty3" name="qty3" value=""><br/>
    <a href=""><img src="add-icon.png" onmouseover="blabla();"></img></a>
    <a href=""><img src="delete-icon.png" onmouseover="lastog();"></img></a>
  </form>
</body>
</html>

我还尝试使用通常的 for 循环来迭代它,但我无法使其工作:

function blabla(){
    for (int i=0; i<arr.length; i++){
        var a= document.x.qty[].value;
        var b=document.x.qty2[].value;
        var pa=parseInt(a);
        var plusqty= pa + 1;
        var txt = plusqty;
        var tbox = document.getElementById('qty');
        if (tbox)
        {
            tbox.value = txt;
        }
    }
}

最佳答案

您需要使用bracket notation访问名称中包含特殊字符的属性,如下所示:

var a = document.x["qty[]"].value;
var b = document.x["qty2[]"].value;

不过,如果他们有 ID,那就容易得多:

var a = document.getElementById("qty").value;

或者例如循环遍历所有具有该名称的内容:

var qtyElements = document.getElementsByName("qty[]");
for(var i=0; i<qtyElements.length; i++) {
  alert(qtyElements[i].value);
}

关于javascript - 如何让数组在 JavaScript 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4232768/

相关文章:

javascript - 检查对象 JavaScript 中是否已存在值

c - 调用数组数据类型进行打印的不同方式?

javascript - 与 TypeScript react : Type is not assignable to type 'IntrinsicAttributes'

javascript - knockout 'flickering' 问题

javascript - jquery动态添加html字段遇到神秘问题

java - “2D”数组数独谜题用枚举进行检查。尽管调试仍无法理解我自己的程序的流程

c - 将二维数组(矩阵)保存到 C 函数内的二进制文件

c - 如何将字符串 block 转换为字符串数组

javascript - Leaflet getBounds() 返回大于 180 的经度

javascript - Marketo 隐藏字段更新