Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

node.js - javaScript function code only fires on the first row of the table

i am trying to create a delete method using fetch API, on when i click on the first row of the table the javaScript function works but if i click on any other column that is not the first one, the function doesn't work.

the script function :

    <script>
    var trashcan = document.querySelectorAll('a.delete_category_a');

    for (let i = 0; i < trashcan.length; i++) {
        trashcan[i].addEventListener("click", function() {
            const url = `/halalMunchies/delete-category/${trashcan.dataset.doc}`;

            fetch(url, {
                    method: 'DELETE'
                })
                .then((response) => response.json())
                .then((data) => window.location.href = data.redirect)
                .catch(err => console.log(err));
        });

    }
</script>

the delete function in the controller :

    exports.deleteCategory = (req, res, next) => {

    console.log('DELETE  CATEGORY /delete-category');

    const id = req.params.id;

    categorySchema.findByIdAndDelete(id)
        .then(result => {
            res.json({ redirect: '/halalMunchies/all-categories' });
        })
        .catch(err => {
            console.log(err);
        });

};

the ejs file table

<tr>

    <% categoryiesList.forEach(function (category) {%>
        <td>
            <%=category.categoryName %>
        </td>




        <td>
            <center> <a href="<%=`/halalMunchies/update-category/${category._id}`%>" style="color: green"> Edit </a> </center>
        </td>



        <td>

            <center> <a type="button" class="delete_category_a" data-doc="<%=category._id%>" style="color: red "> Delete </a> </center>

        </td>

</tr>
<%})%>

that error occurs when i click on the delete tag to run the eventlistner and it refers to the the >>

   const url = `/halalMunchies/delete-category/${trashcan.dataset.doc}`;

Error on the webConsole :

Uncaught TypeError: Cannot read properties of undefined (reading 'doc') at HTMLAnchorElement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...