簡體   English   中英

在空白數組javascript中顯示數據。 <div>

[英]display data in blank array javascript. <div>

到目前為止,我已經能夠想出這樣的東西。 而且我已經能夠將某些東西發送到陣列,但在顯示器中,這是迄今為止我無法實現的。

因此我在問,我如何展示它?

<!doctype html>
<html>

<head>
    <script type=text/javascript>
    var array = [];

    function add_element_to_array() {
        array.push(document.getElementById("institution_name").value);
        array.push(document.getElementById("degree_obtained").value);
        array.push(document.getElementById("honors_acheieved").value);

        document.getElementById("institution_name").value = "";
        document.getElementById("degree_obtained").value = "";
        document.getElementById("honors_acheieved").value = "";
    }

function display_array()
{
    // Display array
}

    </script>
</head>
<title>Test Javascript</title>
<h1>Test JS</h1>

<body>
    <form name="xform" id="xform" method="post" action="samris.php" /> Institution Name:
    <input type="text" name="institution_name" id="institution_name" /> </br>
    Degree Obtained:
    <input type="text" name="degree_obtained" id="degree_obtained" />
    </br>
    Honors Achieved:
    <input type="text" name="honors_acheieved" id="honors_acheieved" />
    </br>
    </p>
    <input type="button" name="Add" id="add" value="add" onclick="add_element_to_array()" />
    </form>
    <div onload= display_array()>
    </div>
</body>

</html>

要顯示數組:

function display_array(){
    var display = array.join('<br>');
    this.innerHTML = display; // only works if you call it inline (except onload).

    /* OR */

    // works everywhere when you add an id to the div except onload (see explanation below).
    document.getElementById('display').innerHTML = display;
}

/* ... in the HTML ... */
<div id="display"></div>

但是,由於onload=display_array()您仍然無法在div顯示它。

加載div ,將調用display_array() 但是當它被加載時, array仍然是空的,因為onclick=add_element_to_array()還沒有添加任何內容。

要做到這一點,你可以在add_element_to_array()調用display_array() ,如下所示:

function add_element_to_array(){
    /*
      your code
    */

    display_array();
}

或者,您需要刪除onclick並在<script>替換addEventListener 但是,您需要將<script>標記移動到<body>標記的底部,或者實現類似於jQuery的ready()的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM