简体   繁体   中英

how to count clicks on an element other than a button?

I have an empty box in the footer section, which is situated in the div

<footer>
<div>
</div>
</footer>

I would like to write a function in javascript that would count the number of clicks in the div, and display the number of clicks in the same div. I am wondering how to achieve this without touching the html. I have seen how to achieve this with a button, but how can I achieve this with a div? thanks

Use .querySelector , if you dont to want add any ID or Class.

 var elem = document.querySelector('footer div'); let countClicks = 0; elem.onclick = function() { countClicks++; elem.textContent = countClicks };
 div { padding:10px; background: #339900; color: #fff; font-size: 44px; }
 <footer> <div></div> </footer>

 var root = document.getElementById('root'); root.onclick = function() { var elem = document.getElementById('count'); elem.innerHTML = +elem.innerText + 1; };
 #count { font-size: 40px; font-weight: bold; }
 <footer> <div id="root">Click HERE</div> <div id="count"></div> </footer>

I've created a div and filled it with a colour to make it easily distinguishable. Clicking on the div will produce a pop-up where the count increments with each click.

<!DOCTYPE html>
<html>

<style>
    div {
        width: 500px;
        height: 100px;
        border: 1px solid grey;
        background-color: blue;
    }
</style>

<head> </head>

<body>
    <script>
        let count = 0;

        function counter() {
            count = count + 1;
            alert(count);
        }
    </script>

    <div onclick="counter()"> </div>
</body>

</html>

Here is the solution.

 const div = document.querySelector('footer > div'); div.addEventListener('click', () => { const previousValue = Number.parseInt(div.innerText || 0); div.innerText = previousValue + 1; });
 footer div { width: 100px; height: 100px; background: #ccc; }
 <footer> <div> </div> </footer>

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