javascript - 在 <a> 元素上使用 onclick

标签 javascript html

我有一个包含 href 属性的 a 元素。单击它会删除数据,因此我希望用户确认该操作。 href 属性指的是一个 php 文件,其中包含 GET 参数中将删除的数据的 id。我添加了一个 onclick 属性,它应该执行以下 JS 片段(它显示一个要求确认的语义 UI 模式):

    confirmmodal = function () {
    beforeunload = function () {
        $('.ui.basic.modal')
            .modal({
                closable: false,
                onDeny: function () {
                    return false;
                },
                onApprove: function () {
                    return true;
                }
            })
            .modal('show')
        ;
}
}

但是当我运行它时,它仍然会转到删除数据的页面(尽管我还没有构建它,所以没有删除任何内容)。是否有一个选项可以以某种方式使 onclick 属性优先于 href 属性?

最佳答案

您需要添加event.preventDefault()在代码末尾。

例如:

<a href="somePage.php" onclick="showDialog(event)">Delete</a>



function showDialog(e) {
    // custom code to show dialog here
    e.preventDefault();
}

关于javascript - 在 <a> 元素上使用 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38937197/

相关文章:

php - 请求 MP3 文件时设置 apache 为 PHP 提供服务

javascript - 如何使 div 与其他 div 一起拖动

javascript - 更好的做法 : Always get a range of 6 Items out of an array

javascript - Amazon S3 POST,事件何时完成?

php - 使用 php 在 iframe 内重定向

jquery - 不要对每个类(class)家长隐藏第一个 child

javascript - 为什么 jQuery 的 .change() 事件仅在单击鼠标右键时触发?

javascript - Vue.js 无法使用模板正确渲染

javascript - 每 1 分钟显示和隐藏 div

html - 复选框出现 gary 并在 Galaxy Built in 浏览器和 Maxthon 中选中