简体   繁体   中英

HTML page keeps reloading after click event

Hi I have a small website, which keeps reloading after a click event. How can I prevent this?

PS: I'm only allowed to use pure JS.

HTML

Cookie Clicker

</head>
<body>
    <header>
        <h1>Points: </h1>
        <span id="score"></span>
    </header>
    <div class="container">
        <div>
            <a href="" onclick="addPoints(1)">
                <img src="assets/graphics/Friis.png" />
            </a>
        </div>
    </div>

    <script src="assets/scripts/cookieClicker.js"></script>
</body>
</html>


JS

var points = 0,
    score = document.getElementById("score");

function addPoints(increase) {
    console.log('hit');
    points += increase;

    score.innerHTML = '' + points;
};

You can modify only your html and it works:

<a href="javascript:void(0);" onclick="addPoints(1)">

Some people make this:

<a href="#" onclick="addPoints(1)">

But this is an anchor that scrolls your page to top. If you need to make by javascript, search about event preventDefault .

EDIT

Read about void javascript function:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

It's good to understand behaviour.

Instead of using onClick you can just change the href to run the function. For example:

<a href="javascript:addPoints(1);">

update your code to:

<a href="" onclick="addPoints(1);return false">

or

<a href="" onclick="return addPoints(1)">

and let your function addPoints return false. Upside of this is that you can actually let the href link to a page in case addPoints reaches a certain level for instance. If addPoints returns true the link will take the user to that page, return false will keep the user on the current page.

that happens because you code contain

   <a href="" onclick="addPoints(1)"> // These Can Reload Same Page
   <a href="#" onclick="addPoints(1)"> // Modify upper code to these code

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