簡體   English   中英

點擊事件后HTML頁面不斷重新加載

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM