ASP.NET MVC循环生成元素后JS仅获取单个ID值问题求助
ASP.NET MVC循环中按钮/卡片点击始终获取第一个ID的问题解决
问题根源
HTML规范要求页面中ID必须唯一,你在foreach循环里给卡片和按钮都使用了固定ID(card、AddToBasket),导致渲染后页面出现多个相同ID的元素。而jQuery的$("#AddToBasket")只会匹配DOM中第一个带有该ID的元素,所以无论点击哪个产品,都只会拿到第一个产品的ID。
解决方法
方案一:直接传递ID参数(最简单直接)
修改视图中的点击事件,把当前产品的ID直接作为参数传给JS函数:
@foreach (var shoe in Model) { <div class="shoeCard card bg-dark col-1 me-3 mb-3"> @if (shoe.Gender == "Male") { <div class="shoeCardBg bg-primary z-1"></div> } else { <div class="shoeCardBg bg-danger z-1"></div> } <img src="@shoe.ImgUrl" class="card-img-top z-3" alt="@shoe.Name" style="position:relative;"> <!-- 传递当前产品ID给Redirect函数 --> <div class="card-body" onclick="Redirect(@shoe.ID)"> <h5 class="card-title text-light fw-bold">@shoe.Name</h5> <p class="card-text text-secondary lh-sm">@shoe.Gender</p> <p class="card-text text-secondary lh-sm">@shoe.Brand</p> <h4 class="card-text text-light lh-sm">£@shoe.Price</h4> </div> <!-- 同样给AddToBasket传递ID --> <button onclick="AddToBasket(@shoe.ID)" class="btn btn-light mb-2">Add to Basket</button> </div> }
然后修改JS函数,直接接收ID参数:
function Redirect(id) { window.location.href = '@Url.Action("Product", "Home")/' + id; } function AddToBasket(id) { // 这里使用传入的id处理添加购物车逻辑 console.log("要添加购物车的产品ID:", id); }
方案二:使用类选择器+Data属性(符合HTML规范,推荐)
把重复的ID换成类,用data-id属性存储产品ID,再通过事件绑定获取对应值:
@foreach (var shoe in Model) { <div class="shoeCard card bg-dark col-1 me-3 mb-3"> @if (shoe.Gender == "Male") { <div class="shoeCardBg bg-primary z-1"></div> } else { <div class="shoeCardBg bg-danger z-1"></div> } <img src="@shoe.ImgUrl" class="card-img-top z-3" alt="@shoe.Name" style="position:relative;"> <!-- 用类代替ID,添加data-id存储产品ID --> <div class="card-body card-item" data-id="@shoe.ID"> <h5 class="card-title text-light fw-bold">@shoe.Name</h5> <p class="card-text text-secondary lh-sm">@shoe.Gender</p> <p class="card-text text-secondary lh-sm">@shoe.Brand</p> <h4 class="card-text text-light lh-sm">£@shoe.Price</h4> </div> <!-- 同样用类+data-id --> <button class="btn btn-light mb-2 add-to-basket" data-id="@shoe.ID">Add to Basket</button> </div> }
然后用jQuery绑定事件,通过data()方法获取ID:
$(function() { // 卡片点击跳转事件 $('.card-item').click(function() { var id = $(this).data('id'); window.location.href = '@Url.Action("Product", "Home")/' + id; }); // 添加购物车事件 $('.add-to-basket').click(function() { var id = $(this).data('id'); // 处理添加购物车逻辑 console.log("要添加购物车的产品ID:", id); }); });
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

