点击事件后HTML页面不断重新加载

3

嗨,我有一个小网站,在点击事件后会不断刷新。我该如何防止这种情况发生?

附注:我只能使用纯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;
};

1
可能是[如何在没有“#”的情况下通过onclick防止重新加载?](https://dev59.com/_2Mm5IYBdhLWcg3wX94W)的重复问题。 - JJJ
1
href 更改为 href="javascript:;" 或传递 event 并调用 preventDefault() - haim770
4个回答

6
您只能修改您的HTML,这样就可以起作用:
<a href="javascript:void(0);" onclick="addPoints(1)">

有些人会制作这样的东西:

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

但这是一个将您的页面滚动到顶部的锚点。如果您需要通过javascript实现,请搜索有关event preventDefault的信息。

编辑

了解有关void javascript函数的信息:

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

理解其行为是很好的。


很棒的解决方案,比我的好!我没有想到那个。 - morha13

3

请将您的代码更新为:

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

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

并让您的函数addPoints返回false。好处是,如果addPoints达到一定级别,您实际上可以让href链接到页面。如果addPoints返回true,则链接将带用户到该页面,而返回false则会使用户留在当前页面。


2

不必使用onClick,您只需更改href以运行函数即可。例如:

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

1
这是因为您的代码包含了。
   <a href="" onclick="addPoints(1)"> // These Can Reload Same Page
   <a href="#" onclick="addPoints(1)"> // Modify upper code to these code

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接