单击事件不会触发使用Html.ActionLink生成的链接

时间:2015-11-17 11:54:32

标签: javascript jquery asp.net

我有一个ActionLink,如下所示:

@Html.ActionLink("-Pg", "SupprimerPage", "Section", 
new { pageId = @item.Id }, new { @id = "ConfirmDeletePage", @class = "editLink", style 
= "width:30px" })

我的剧本:

  $(document).ready(function () {
    $(document).on('click', '#ConfirmDeletePage', function () {
        var x=confirm("Confirm delete page?");
        console.log(x);
        if (x == true){
            return true;
        }
        else {
            return false;
        }
    });
});

当我使用带有<a>标记的硬编码链接时,它可以正常工作。但是当我尝试使用Html.ActionLink生成链接时,不会调用事件处理程序。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

对于你的问题“当我点击Yes时,ActionLink中的方法没有被调用”这是因为你在yes按钮上返回yes所以在执行你的函数后它跟随链接“href”这就是为什么它似乎是方法在ActionLink中没有被调用,只返回false或在true部分内使用event.preventDefault();,按下yes按钮

     $(document).ready(function () {
        $(document).on('click', '.editLink', function (event) {
            var x=confirm("Confirm delete page?");
            console.log(x);
            if (x == true){
     
              return true;
    
            }
            else {
                alert('Pressed NO')
                return false;
            }
        });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a href="http://hello.com" class="editLink" >Click me !</a>

了解更多内容anchor-tag-with-javascript-onclick-event

答案 1 :(得分:0)

如果它与硬编码链接一起使用,但在使用ActionLink时则不行,这意味着ActionLink必须生成与硬编码链接不同的内容,这意味着您的jQuery选择器(#ConfirmDeletePage)未找到该元素

您可以使用浏览器的开发人员工具来检查ActionLink生成的<a...标记。

根据问题Html.ActionLink with a specified HTML id,您可能需要将@id = "ConfirmDeletePage"更改为id = "ConfirmDeletePage"

相关问题