父页面中的JQuery未检测到局部视图中的id元素

ksg*_*ksg 3 javascript asp.net-mvc jquery razor asp.net-mvc-4

我有一个动态id元素"deleteSite"(在局部视图中)点击它将从表中删除该站点.当我点击它时,除第一个元素外,不会调用jquery函数(在父页面中).请帮我看看这里出了什么问题.

页面通常是正常加载的,但在分页期间通过ajax加载

这是我的部分观点

@model IPagedList<MvcSIMS.Models.Site>
 <table class="table table-bordered table-hover table-striped">
            <thead>
                <tr>
                    <th style="width: auto;">SlNo</th>
                    <th>SiteName</th>
                    <th>Remarks</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>                    
                @foreach (var item in Model.Select((x, i) => new { Data = x, Index = i }))
                {
                    <tr>
                        <td>@(item.Index + ((Model.PageNumber - 1) * Model.PageSize) + 1)</td>
                        <td>@Html.DisplayFor(modelItem => item.Data.SITENAME)</td>
                        <td>@Html.DisplayFor(modelItem => item.Data.REMARKS)</td>
                        <td>
                            <a href="@Url.Action("Edit", new { id = item.Data.ID })" class="btn btn-sm btn-primary">
                                <span class="glyphicon glyphicon-edit" aria-hidden="true"></span>
                            </a>
                            <a id="deleteSite" href="@Url.Action("Delete", new { id = item.Data.ID })"
                            class="btn btn-sm btn-danger delete">
                                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                            </a>
                        </td>

                    </tr>
                }                    
            </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

这就是我的jquery正在做的事情 -

 $(function () {

 //Delete function
        $("#deleteSite").click(function () {
            alert("hai");
            return false;
  })
};
Run Code Online (Sandbox Code Playgroud)

mat*_*mmo 5

那是因为id 必须是唯一的,所以jQuery只返回一个.考虑使用类来标识您的按钮,例如:

class="delete-site"
Run Code Online (Sandbox Code Playgroud)

然后将你的jQuery更改为(我们也委托事件,因此只有一个事件可用于n个项目,这意味着以后通过AJAX添加的项目仍将为此事件注册):

$(document).on("click", ".delete-site", function () {
    alert("hai");
    return false;
});
Run Code Online (Sandbox Code Playgroud)