简体   繁体   English

如何计算按钮以外的元素的点击次数?

[英]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我在页脚部分有一个空框,它位于 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.我想在 javascript 中写一个 function 来计算 div 中的点击次数,并显示同一 div 中的点击次数。 I am wondering how to achieve this without touching the html.我想知道如何在不接触 html 的情况下实现这一目标。 I have seen how to achieve this with a button, but how can I achieve this with a div?我已经看到如何使用按钮来实现这一点,但是如何使用 div 来实现呢? thanks谢谢

Use .querySelector , if you dont to want add any ID or Class.如果您不想添加任何 ID 或类,请使用.querySelector

 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.我创建了一个 div 并用颜色填充它以使其易于区分。 Clicking on the div will produce a pop-up where the count increments with each click.单击 div 将产生一个弹出窗口,其中每次单击计数都会增加。

<!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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM