jQuery append()刷新页面

时间:2018-12-07 19:51:32

标签: jquery

我有一个向表添加一行的简单任务,但是由于执行了append命令后,由于某种原因,整个页面都会刷新。我试图在小提琴上重新创建它,但是在那里出现了404错误。

https://jsfiddle.net/9fp8scoj/3/

<!doctype html>
<html>
<meta charset="UTF-8"> 
<head>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script >
        $(document).ready(function(){
            $("#add").click(function(){

                $("table tbody").append('<tr><td>a</td><td>b</td><td>c</td></tr>');
            });
        });
    </script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title text-center">Table</h3>
        </div>
        <form id="inputForm" class="form-inline">
            <div class="form-group">
                <input class="form-control" type="text" id="first" placeholder="First name"/>
                <input class="form-control" type="text" id="last" placeholder="Last name"/>
                <input class="form-control" type="text" id="place" placeholder="Place"/>
            </div>
            <button class="btn btn-primary" class="add-row" id="add">Add person</button>
        </form>
        <div class="panel-body">
            <table id="people" class="table" style="width:100%;">
                <thead>
                    <tr>
                        <th>Firstname</th>
                        <th>Lastname</th>
                        <th>Place</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Jon</td>
                        <td>Snow</td>
                        <td>Great Wall</td>
                    </tr>
                    <tr>
                        <td>Arya</td>
                        <td>Stark</td>
                        <td>Winterfell</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>

2 个答案:

答案 0 :(得分:0)

在大多数浏览器中,您的按钮将默认为一种提交类型(请参见here),这将提交包裹的表单,并触发您所看到的页面刷新。您需要将type="button"添加到ID为add的按钮上

答案 1 :(得分:0)

您在这里错过了几件事。首先,您需要提及按钮类型,例如type="button"按钮,否则它被视为提交按钮,这就是由于表单提交而刷新页面的原因。然后更正您的单击选择器。同样,您的按钮具有attribute之类的<button class="btn btn-primary" class="add-row"之类的2类。请参阅我在下面添加的代码段。

<button class="btn btn-primary add-row"