[英]HTML page keeps reloading after click event
嗨,我有一个小网站,在点击事件后不断重新加载。 我怎么能阻止这个?
PS:我只允许使用纯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;
};
你只能修改你的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
理解行为很好。
您可以只更改href来运行该函数,而不是使用onClick。 例如:
<a href="javascript:addPoints(1);">
将您的代码更新为:
<a href="" onclick="addPoints(1);return false">
要么
<a href="" onclick="return addPoints(1)">
并让你的函数addPoints返回false。 这样做的好处是,如果addPoints达到某个级别,你实际上可以让href链接到一个页面。 如果addPoints返回true,则链接将把用户带到该页面,返回false将使用户保持在当前页面上。
这是因为您的代码包含
<a href="" onclick="addPoints(1)"> // These Can Reload Same Page
<a href="#" onclick="addPoints(1)"> // Modify upper code to these code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.