简体   繁体   中英

How do I prevent that when the link in the code is clicked this link takes me to the page that makes reference

I found this code

<body>
<div id="div1">
What is 2+2?
</div>
<div id="div2">
<a href="answer.html" id="answer_link">Get the answer</a>
</div>
</body>

then the javascript

var d1 = document.getElementById("div1");
var a_link = document.getElementById("answer_link");
a_link.onclick = function() 
{
   d1.innerHTML = "That is easy, the answer is <strong>4</strong>!";
   return false;
};

so this code works because it changes the inner html in the div1 and doesn't load the page that the link makes reference but what if i want to use event listeners? i write this

a_link.addEventListener( 'click', function(){
    d1.innerHTML = "That is easy, the answer is <strong>4</strong>!";
    return false;
}, false);

but it doesn't prevent the link to load the reference how can i use an event listener that works the same way that the little piece of code of above?

Use e.preventDefault() for normal browsers and event.returnValue in older IE browsers:

aLink.addEventListener( 'click', function(e){
    d1.innerHTML = "That is easy, the answer is <strong>4</strong>!";
    if (e && e.preventDefault) {
        e.preventDefault();
    } else {
        window.event.returnValue = false;   // guess who - IE
    }
}, false);

Actually, older versions of IE don't even support addEventListener() , so the IE part of the code is only needed if you're using the same callback function with attachEvent() as you are with addEventListener() which I do.

Have you tried prevenDefault ? This may help you control the functionality of your click event.

Documentation here - https://developer.mozilla.org/en/DOM/event.preventDefault

Also, in your code. You switch from referencing the <a> tag with a var named a_link and a var named aLink . Is this a typo or just a change in your implementation?

Why does your anchor need a URL if you're not going to load it? Couldn't you just use "#" or something?

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