简体   繁体   中英

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.

You don't get the alert because your code changes all the "click" handlers, removing the ones coded in 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 .

You can do it really easily with JQuery:

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

you can test it in this fiddle: http://jsfiddle.net/kvCwW/

You need to add e.preventDefault() to your click handler:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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