Nodejs JavaScript添加到按钮没有响应

时间:2019-08-17 09:45:25

标签: javascript node.js

我在表中的每个数据库条目都有一个按钮。由于表格不能在表格中,因此我无法使用表格提出请求。我向每个按钮添加了一部分javascript,这些按钮应发出带有数据库ID的get请求并重定向到另一个页面。它似乎不起作用。我测试了创建虚拟表单并在页面上进行相同的获取请求,并且该方法有效。任何想法为什么这不起作用?

Nodejs文件路由器

const express = require('express')
const router = express.Router()

router.get('/testRedirect/:id', (req, res) => res.render('pages/about'))

module.exports = router

<!DOCTYPE html>
<html>

<head>
    <% include ../partials/header.ejs %>
</head>

<body>
    <% include ../partials/nav.ejs %>

        <div class="container">
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">Id</th>
                        <th scope="col">Name</th>
                        <th scope="col">Edit</th>
                        <th scope="col">Delete</th>
                    </tr>
                </thead>
                <tbody>
                    <% results.forEach(function(r) { %>
                        <tr>
                            <th scope="row">
                                <%= r.id %>
                            </th>
                            <th scope="row">
                                <%= r.name %>
                            </th>
                            <td>
                                <button type="submit" id=<%=r.quiz_id %> class="btn btn-primary">Edit</button>
                                <script type="text/javascript">
                                    $(function() {
                                        var id = <%=r.id %>
                                        var idString = "#" + id
                                        $(idString).click(function() {
                                            $.get('/testRedirect/' + id)
                                        })
                                    });
                                </script>
                            </td>
                            <td>
                                <button type="submit" id=<%=r.Id %> class="btn btn-primary">Delete</button>
                                <script type="text/javascript">
                                </script>
                            </td>
                        </tr>
                        <% }); %>
                </tbody>
            </table>
        </div>

        <form action="/testRedirect/1" method="GET">
            <button type="submit" class="btn btn-primary">Submit</button>
        </form> 
</body>

</html>

1 个答案:

答案 0 :(得分:1)

您真的需要每个按钮一个脚本块吗?您不能使用onclick属性:

<button type="button" id=<%=r.quiz_id %> onclick="location.href='/testRedirect/#<%=r.quiz_id %>'" class="btn btn-primary">Edit</button>
相关问题