簡體   English   中英

Javascript 函數在 jsp 頁面中不起作用

[英]Javascript function not working in jsp page

我想在我的 jsp 頁面中使用 javascript 以便將輸入框的值插入到表格行中。

我的 Jsp 頁面:-

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Title</title>

    <script type="text/javascript">
        function addData(){
            var x = 1;
            var a = document.getElementById('area').value; 

            var table = document.getElementByTagName('table')[0];

            var row = table.insertRow(table.rows.length);

            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);

            cell1.innerHTML = x++;
            cell2.innerHTML = a;
        }
    </script> 

</head>

<body>
    <h2>Area...</h2>
    Area: <input type="text" id="area" name="area" required/><label>sq. ft.
    <button onclick="addData();">Add To Table</button>
    </br></br> 


        <div>
            <h2>Area Table...</h2>
            <table border="1">
                <tr>
                    <th>Section</th>
                    <th>Area</th>
                </tr>
                <tr>
                    <td>1</td>
                    <td>125.4485</td>
                </tr>
            </table>
        </div>
    </body>
</html>

在這里,我想從輸入框中將一行插入到表格中。 但是沒有插入值。

代碼有沒有問題。

使用瀏覽器的控制台開發工具,查看錯誤,
這是錯誤:

未捕獲的類型錯誤:document.getElementByTagName 不是 HTMLButtonElement.onclick (a.html:28) 的 addData (a.html:11) 中的函數

這意味着 javascript 無法識別此函數,因此您必須查看該函數的正確表示法

getElementsByTagName

錯別字

試試這樣, TagName是多重選擇器。你缺少s

var table = document.getElementsByTagName('table')[0];

代替

 var table = document.getElementByTagName('table')[0];

 function addData() { var x = 1; var a = document.getElementById('area').value; var table = document.getElementsByTagName('table')[0]; var row = table.insertRow(table.rows.length); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = x++; cell2.innerHTML = a; }
 <h2>Area...</h2> Area: <input type="text" id="area" name="area" required/><label>sq. ft. <button onclick="addData();">Add To Table</button> </br></br> <div> <h2>Area Table...</h2> <table border="1"> <tr> <th>Section</th> <th>Area</th> </tr> <tr> <td>1</td> <td>125.4485</td> </tr> </table> </div>

請將拼寫getElementByTagName更正為getElementsByTagName

暫無
暫無

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

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