JavaScript prevent a tag open the page of its url

created at 11-22-2021 views: 4

Need to add a click event to the a tag, and deal with some affairs before jumping, so some processing needs to be done

The methods to prevent the a tag from jumping are:

method 1

<a href="javascript:void(0)">Baidu</a>

void is an operator, void(0) returns undefined, the address does not jump

<a href="javascript:;">Baidu</a>

Same as above, returns undefined

method 2

<a href="http://google.com" onclick="show()">google</a> 
<script>
    function show(){
        alert("I did not go forward");
        return false;
    }
</script>

After the above code is executed, it will still go to the url. When the a tag is clicked, the executed code is equivalent to this:

obj.onclick=function(){
    show();
}

The show() method has no return value, it is undefined. So it still jumps.

The point is here: in the working mechanism of the event handling function, when an event handling function is added to an element, once the event occurs, the corresponding JavaScript code will be executed, and the return value of the called JavaScript code is passed to the event handling function. When we add the onclick event handler to the a tag and click a to trigger it, if the corresponding JavaScript code returns `true`, the onclick event handler will think that the link has been clicked, and the same will be true if it returns false, Think that the link has not been clicked.
So it can be written like this:

<a href="http://www.google.com" onclick=" myjs(); return false;">google</a>
<a href="http://www.google.com" onclick=" return false; ">google</a>
created at:11-22-2021
edited at: 11-22-2021: