javascript - JS event running issues on <a> elements and <input> elements
黄舟
黄舟 2017-06-28 09:22:39
0
2
626
    window.onload = function () {
        var a = document.getElementById("a");
        var btn = document.getElementById("btn");
        
        function aFn () {
            console.log("aFn");
        }
        function btnFn () {
            console.log('btnFn');
        }
        a.onclick = function () {
            aFn();
        }
        btn.onclick = function() {
            btnFn();
        }
        console.log('global');
    }

When I clicked on these two events, something different happened! ?

For the a element: first run the code and output console.log('global'), then click a to draw the point element, as shown in the figure:

For the button element: first run the code, output console.log('global'), and then click btn, as shown in the figure:

overall:

In other words, the click event is executed differently for the two elements. The click event on the a element will execute the code outside the function once. Why is this? !

Someone just said that it is normal to use Chrome in his environment. I changed the console to alert, and it is still the same. I also use chrome.
But on IE, this is not the case. After running, a global alert will pop up. After clicking the a tag, the function will pop up first, and then the page will jump directly. There will be no situation like in chrome. What's going on! (Editor: HBuilder)

PS: When I was trying to write a carousel image example, I used the a element as an arrow button, which directly caused my image to be unable to switch 55555 (equivalent to and execution when clicking a Once the code in the global scope...)

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
三叔

Hahaha, it’s really an interesting question. I found out after reading it for a while.
It’s because your a tag does not have the href attribute set. Clicking it will refresh the page.
Equivalent to: log global -> Click log a -&gt ; Refreshed log global again

It is normal if the second global does not exist. You can set href="#" in the a tag and see.

Also, please make the fonts in the screenshots bigger next time...I can’t see clearly due to my bad eyesight.

仅有的幸福

Write event.preventDefault();

in the a tag event binding function
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template