简体   繁体   English

使用JavaScript和警报禁用HTML链接

[英]Disable HTML links using JavaScript and Alerts

Here is my code: 这是我的代码:

    function Alert()
{   
alert("Please click on OK to continue.")
}
window.onload = function()

    {       
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        anchors[i].onclick = function() {return(false);};
    }
};

the link is coded at this: 链接的编码如下:

<a href="main.html" onclick="Alert()"> Link to Main Page</a>

When I put this to test, the link does not work (as expected), but I don't get the alert box that's supposed to say "Please click on OK to continue." 当我对此进行测试时,该链接不起作用(按预期方式),但是我没有看到提示框为“请单击确定以继续”的警告框。 when the link is clicked. 单击链接时。 Can someone give me advice on how to fix this? 有人可以给我建议如何解决此问题吗? Ultimately, once the page loads and the the link is clicked, it should show and alert that says "Please click on OK to continue." 最终,页面加载并单击链接后,它应该显示并提示“请单击确定以继续”。 and nothing should happen. 而且什么也不会发生。 I know how to do this by changing the "href" attribute, but I need to know how to do it without changing that part. 我知道如何通过更改“ href”属性来执行此操作,但是我需要知道如何在不更改该部分的情况下执行此操作。

You don't get the alert because your code changes all the "click" handlers, removing the ones coded in HTML. 您不会收到警报,因为您的代码更改了所有“单击”处理程序,从而删除了HTML编码的处理程序。 There's only one "onclick" property on the DOM nodes involved, so as soon as your script runs the handler that calls "Alert()" is replaced by the one that just returns false . 所涉及的DOM节点上只有一个“ onclick”属性,因此,一旦您的脚本运行调用“ Alert()”的处理程序,该处理程序将被仅返回false的处理程序替换。

You can do it really easily with JQuery: 您可以使用JQuery真正轻松地做到这一点:

$('a').on('click',function(e){
    e.preventDefault();
    alert('your alert message');
});

you can test it in this fiddle: http://jsfiddle.net/kvCwW/ 您可以在此小提琴中对其进行测试: http : //jsfiddle.net/kvCwW/

You need to add e.preventDefault() to your click handler: 您需要将e.preventDefault()添加到点击处理程序中:

anchors[i].addEventListener("click", function(e) {
    e.preventDefault();
    return false;
}, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM