html - 访问为循环中的每个项目创建的提交按钮——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()
解决方案
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.
我认为这应该做的工作。
推荐阅读
- python - 使用 TimeDistributed 层在 Keras 中构建有状态 RNN 时出错
- facebook - 如何在 React 站点中为 Facebook Pixel 的表单手动添加自动高级匹配?
- css - 使用 SASS 向线性渐变添加不同的颜色
- javascript - 根据鼠标位置暂停和恢复 SetInterval
- r - 通过 geom_smooth 添加回归线,在一张图中有和没有颜色分组
- ruby-on-rails - 使用 Sidekiq 的 RSpec 邮件测试发送空 [] 错误
- java - 如何将 SearchView 查询添加到 FirestoreRecyclerOptions?
- path - 在域路径上使用 Google ReCaptcha
- php - 基于 WooCommerce 中订单总额的运费折扣百分比
- c# - 在具有内存限制的 Docker 容器中运行 .NET Core 应用程序