search

Home  >  Q&A  >  body text

javascript - JS event running issues on <a> elements and <input> elements

    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...)

黄舟黄舟2710 days ago636

reply all(2)I'll reply

  • 三叔

    三叔2017-06-28 09:24:39

    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 -> ; 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.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-28 09:24:39

    Write event.preventDefault();

    in the a tag event binding function

    reply
    0
  • Cancelreply