将数据发布到二维数组javascript

时间:2015-03-27 06:54:49

标签: javascript

我有这样的来源:

<label>Name:</label>
<input type="text" name="text1"/>
<label>Weight:</label>
<input type="text" name="text2"/>
<button onclick="myfunction">Add</button>

<p id="demo"></p>

<script>
var array = new Array();

function myFunction() {
    var text1 = document.getElementById("text1").value;
    var text2 = document.getElementById("text2").value;

    if(text1 == "" || text2 == ""){
        alert("Empty!!");
    }else{
        array = {'data' : [{"Text1" : text1, "Text2" : text2}]}
    }
}
</script>

我的问题是,如何在java脚本中将每个文本的值发布到二维数组?从技术上讲,我们可以反复将值发布到2D数组,因此数组看起来像:

var data = {{text1,text2},....,{text-n,text-n+1}}

然后在基于2D阵列的表格中找出它。我试过了,但还是不行。我不熟悉javascript。真的需要帮助..

3 个答案:

答案 0 :(得分:1)

每次单击按钮时,都可以将新元素推送到数组中。使用这个数组。

var array = [];

function change() {
    var text1 = document.getElementById("text1").value;
    var text2 = document.getElementById("text2").value;

    if (text1 == "" || text2 == "") {
        alert("Empty!!");
        return;
    }

    array.push({
        'data': {
            "Text1": text1,
            "Text2": text2
        }
    });

    console.log(array);
}

此外,您尝试按ID获取元素,但没有为输入元素分配ID。我在这个Fiddle中纠正了这一点。这很有效,看一看。

答案 1 :(得分:0)

你需要使用Jquery

  var array = {
    'x': { a: 'aaa', c: 'xxx' },
    'y': { b: 'bbb', d: 'yyy' }
   };

在这里使用Jquery

  $.post( '/herp.php', array, function(d) {
     // process response here
  });

答案 2 :(得分:0)

将输入放在表单中,然后在jquery中使用serializeArray