首页 > 解决方案 > 访问为循环中的每个项目创建的提交按钮——HTML jQuery AJAX

问题描述

我有一个愿望清单页面,其中包含每个项目都有一个删除按钮,该按钮是使用表单在循环中创建的,每个按钮都有项目 ID 作为值。每当单击删除按钮以从数据库中删除该项目时,我都想发出发布请求。

但问题是在循环中创建了许多具有相同 id 的按钮,那么如何单独访问它们呢?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>::WISHLIST::</h1>

    {% for wish in wishes %}
        <img src={{wish.image_path}} width="150" height="200">
        </br>
        {{wish.material}}
        {{wish.productType}}
        </br>
        {{wish.price}}
        </br>
        <form method="POST" target="_self">
            <button id="remove_wish" name="remove_wish" type="submit" value={{wish.id}}>Remove</button>
        </form>
        </br>
    {% endfor %}

    <script>
        $(document).ready(function() {
            $('#remove_wish').click(function (event) {
                event.preventDefault();
                alert($('#remove_wish').val())
           $.ajax({
            data : {
                    delete_wish : $('#remove_wish').val()
                    },
                type : 'POST',
                url : '/wishlist/',
                success: function (data) {
                    location.reload();
                },
                error: function (e) {
                    alert('something went wrong')
                }
            });
        });
        })
    </script>


</body>
</html>

在这里,我尝试使用相同的 id,但这仅适用于愿望清单上最顶部的项目,而对于其他项目,它会给出错误:NoResultFound: No row was found for one()

标签: htmljqueryajaxformspost

解决方案


DOM 中不应有多个具有相同 id 的元素。

在您的按钮中更改以下内容:

  • 为按钮添加一个类。比方说remove_wish
  • 将按钮的 id 值更改为wish-{{wish.id}}(例如)。

<button class="remove_wish" id="wish-{{wish.id}}" name="remove_wish" type="submit" value={{wish.id}}>Remove</button>

在您的 AJAX 调用中,更改事件的选择器以侦听类选择器而不是 id 选择器:

$('.remove_wish')

使用substring 函数获取元素的 id :

var id = $(this).attr('id');
var id_value = id.substring(5); //five because "wish-" has five characters.

我认为这应该做的工作。


推荐阅读