如何在Javascript中使用表单值推送2D数组

时间:2018-03-27 08:06:21

标签: javascript html arrays forms

我是JavaScript的新手,并且不知道为什么我的2D数组(每个主要行元素都包含' Word'和#39; Color Value'列元素)不是用用户输入的表格值更新?还有为什么它不显示阵列? 非常感谢任何帮助!

HTML代码:

<html>
    <head>
        Your current list of words to search:
        <p id = "Array"> </p>
    </head>

    <body>

    <form>
        Input Word:<br><br>
        <input type="text" id="wordInputId" ><br>

        <br> Highlight Color: <select name="colortype" id="colorTypeId">
        <br>
        <br>
        <option value="1">Blue</option>
        <option value="2">Green</option>
        <option value="3">Red</option>
        <option value="4">Yellow</option>
        </select>
        <br/>
        <br/>
        <input type="button" name="submit" value="Add Word" onclick="addEntry(   inventory, document.getElementById('wordInputId').value, document.getElementById('colorTypeId').value )"/>
    </form>

    <br>

    <button> Search Page</button>

    <script src="Words.js">

        var inventory = [[]];
        displayInventory(inventory);

    </script>

    </body>
</html>

JS函数(Words.js):

function displayInventory(inventory){
    document.getElementById("Array").innerHTML = inventory.toString();
}


function addEntry(inventory, word, color){
    inventory.push([[word.value],[color.value]]);
    //displayInventory(inventory);
}

2 个答案:

答案 0 :(得分:2)

在同一脚本标记中使用src和脚本行是定义脚本的错误方法。首先,你需要分开它们。然后你的displayInventory函数只在编译脚本时调用一次。您可以通过在click事件上绑定它来检查它。您也不需要使用按钮发送inventory数组。它将在脚本中定义。此外,您第二次获得代码values。这意味着你正试图获得价值,这很糟糕。请检查此代码。

&#13;
&#13;
var inventory = [[]];
function displayInventory(inventory){
    document.getElementById("Array").innerHTML = inventory.toString();
}
function addEntry(word, color){
    inventory.push([[word],[color]]);
    displayInventory(inventory);
}
&#13;
<html>
<head>

</head>   
    <body>
    Your current list of words to search:
    <p id = "Array"> </p>
    <form>
        Input Word:<br><br>
        <input type="text" id="wordInputId" ><br>
        <br> Highlight Color: <select name="colortype" id="colorTypeId">
        <br>
        <br>
        <option value="1">Blue</option>
        <option value="2">Green</option>
        <option value="3">Red</option>
        <option value="4">Yellow</option>
        </select>
        <br/>
        <br/>
        <input type="button" name="submit" value="Add Word" onclick="addEntry(document.getElementById('wordInputId').value, document.getElementById('colorTypeId').value)"/>
    </form>
    <br>
    <button> Search Page</button>
    </body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您不能在src标记上同时拥有script属性和正文。你可以有一个。

所以,你应该像这样构建它:

<script type="text/javascript" src="Words.js"></script>
<script type="text/javascript">

    var inventory = [[]];
    displayInventory(inventory);

</script>