简体   繁体   English

如何添加一个计数器来显示一个 div 元素被点击了多少次?

[英]How do I add a counter to show how many times a div element has been clicked?

I am creating a basic website for a personal project.我正在为个人项目创建一个基本网站。 I have a div element in the code as well.我在代码中也有一个 div 元素。 When a user clicks this particular div element, I want the site to display a counter next to the div element to count how many times it has been clicked.当用户点击这个特定的 div 元素时,我希望网站在 div 元素旁边显示一个计数器来计算它被点击的次数。 I don't need to save anywhere else how many times it has been clicked.我不需要在其他任何地方保存它被点击了多少次。 Is this possible with JS and how could I do this? JS可以做到这一点吗?我该怎么做?

I don't know much Javascript at all, so I haven't known what exactly to try.我根本不知道多少 Javascript,所以我不知道到底要尝试什么。

I want to have a basic counter next to the element to count how many times it has been counted.我想在元素旁边有一个基本计数器来计算它被计算了多少次。 Again, nothing needs to be saved a server.同样,无需将任何内容保存为服务器。 Also, I am not worried about how many times a user can click the div element and add another number.另外,我不担心用户可以单击 div 元素并添加另一个数字的次数。

First you need a counter where you store the number of clicks首先,您需要一个计数器来存储点击次数

let clicks = 0;

Then you need to find your div in the DOM using然后你需要在 DOM 中找到你的 div 使用

document.getElementById() // or
document.getElemenyByClass() // or similar

An example of finding your div would be找到你的 div 的一个例子是

my_div = document.getElementById("click_div");

Then you need to add an Event listener to the div然后你需要在 div 中添加一个Event 监听

Something like this像这样的东西

my_div.addEventListener("click", function(){
  // add code here that increases the /clicks/ variable
});

Welcome to stackoverflow @Gabrielle.欢迎来到stackoverflow @Gabrielle。 I understand that your new to JavaScript and haven't been able to find a meaningful answer to attempt this project.我了解您是 JavaScript 的新手,并且无法找到有意义的答案来尝试这个项目。

Lets start basic first, in JavaScript, we need to store the value of clicks, so we declare a variable让我们先开始basic,在JavaScript中,我们需要存储clicks的值,所以我们声明一个变量

i = 0

Now we want to give that specific div an ID, so lets say <div id="special"> Some Content...</div>现在我们想给那个特定的 div 一个 ID,让我们说<div id="special"> Some Content...</div>

Within our JavaScript code block, we need to reference to special, so we create another variable,在我们的 JavaScript 代码块中,我们需要引用特殊的,所以我们创建另一个变量,

myDiv = document.getElementById("special")

myDiv now is referenced to that special div you want to track. myDiv现在引用了您要跟踪的特殊 div。 Next we create the on click event to track clicks on that element.接下来,我们创建 on click 事件来跟踪对该元素的点击。

myDiv.addEventListener("click",function(){ Clicked. Do something... })

addEventListener tells the DOM that it wants to listen to clicks occurring onto that element only and if so, trigger the instructions inside of the function tag. addEventListener告诉 DOM 它只想监听发生在该元素上的点击,如果是这样,则触发 function 标记内的指令。

Now we increase the counter, or the variable i each time a click occurs, so we use i += 1现在我们增加计数器,或者每次点击时变量i ,所以我们使用i += 1

This way each click that occurs, i adds one to itself.这样,每发生一次点击, i都会自己添加一个。

Lastly we have to show that number to another special ID on the page, I will leave that part "Since its simple" to you to figure out but I will reference it below.最后,我们必须将该号码显示给页面上的另一个特殊 ID,我将把这部分“因为它很简单”留给您自己弄清楚,但我会在下面引用它。

 // Variables i = 0; myDiv = document.getElementById("special"); // Event Listeners myDiv.addEventListener("click", function() { i += 1; console.log(i); });
 <div id="special">Click Me!</div>

Some help with displaying the number inside of your page, go to JS Inner HTML一些帮助显示页面内的数字,go 到JS Inner HTML

Hope this helped!希望这有帮助! Don't forget to thumbs this up if it did!如果有,别忘了点赞!

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>

Do you mean a basic counter like this?你的意思是像这样的基本计数器吗? You can also add the eventlistener to a normal div (doesn't need to be a button element):您还可以将 eventlistener 添加到普通 div (不需要是按钮元素):

JS: JS:

$(document).ready(function() {
      let counter = 0
      document.getElementById("button").addEventListener("click", function(){
        counter++
        document.querySelector(".counter").innerHTML = counter
      });
    });

HTML: HTML:

<button id="button">Click!</button>
<div class="counter">0</div>

First, you need to give your divs labels that javascript can target.首先,您需要提供 javascript 可以定位的 div 标签。 We can use id because they are unique.我们可以使用id因为它们是唯一的。 For example:例如:

<div id="clicker"></div>

The way javascript targets id is via document.getElementById("clicker") javascript 目标id的方式是通过document.getElementById("clicker")

Next, we need to know when the div is being clicked.接下来,我们需要知道 div 何时被点击。 We do this by attaching a "listener" to the div that tracks "clicks":我们通过将“监听器”附加到跟踪“点击”的 div 来做到这一点:

document.getElementById("clicker").addEventListener("click", ...

Now, when a click is detected, that the function (ie code) that is attached to the click will run.现在,当检测到点击时,附加到点击的 function(即代码)将运行。 The following explains the code in the function.下面解释function中的代码。

We use .textContent to retrieve the text content in the div, and assign it to the variable count :我们使用.textContent检索 div 中的文本内容,并将其分配给变量count

let count = document.getElementById("counter").textContent;

Since count is a string, we convert it to numbers first with the parseInt function.由于 count 是一个字符串,我们首先使用parseInt function 将其转换为数字。 Not all the time necessary in javascript as it automatically coverts, but good practice anyhow. javascript 中并非所有时间都需要,因为它会自动转换,但无论如何都是良好的做法。

parseInt(count);

Now that we know it's a number, we can add one to it.现在我们知道它是一个数字,我们可以给它加一个。 This is a short form:这是一个简短的形式:

counter++; // same as saying counter = counter + 1;

Remember how we got the text content from the div with .textContent ?还记得我们如何使用.textContent从 div 获取文本内容吗? We can also set the text content with the same .textContent like so:我们还可以使用相同的.textContent设置文本内容,如下所示:

document.getElementById("counter").textContent = count; //set to new value

Putting it together:把它放在一起:

 // target the "clicker" div and adds a listener to detect clicks document.getElementById("clicker").addEventListener("click", function (event) { // for each click, it will run this function // get current value from "counter" div let count = document.getElementById("counter").textContent; // turn string to integer parseInt(count); // add one count++; // set the new value back to "counter" div document.getElementById("counter").textContent = count; });
 div { display: inline-block; padding: 5px; border: solid 1px gray; }
 <div id="clicker">click here</div><div id="counter">0</div>

Here's a very beginner-friendly way to do it:这是一种非常适合初学者的方法:

HTML and CSS: HTML 和 CSS:
The HTML contains two div elements (each with its own id attribute so our JavaScript code can easily find them.) And the CSS improves the appearance of the HTML. The HTML contains two div elements (each with its own id attribute so our JavaScript code can easily find them.) And the CSS improves the appearance of the HTML.

JavaScript: JavaScript:
Two variables are created, and each one stores a reference to one of the div elements.创建了两个变量,每个变量都存储对其中一个div元素的引用。 An event listener is created, to notice whenever a click event happens on the page and respond by calling the count function.创建了一个事件侦听器,用于在页面上发生click事件时通知并通过调用count function 进行响应。

The count function is created.创建count function。 Most of its statements are wrapped inside an if block, so that the code will only execute if the condition is met.它的大部分语句都包装在if块中,因此代码只有在满足条件时才会执行。 (The triggering condition is that the target of the click event was the div element whose id attribute has the value " clickableDiv ".) (触发条件是click事件的目标是id属性值为“ clickableDiv ”的div元素。)

Now whenever a click happens, if the condition is met, the rest of the code runs:现在每当点击发生时,如果满足条件,代码的 rest 就会运行:

  1. Two variables are created: oldCount and newCount .创建了两个变量: oldCountnewCount
  2. oldCount is assigned a value. oldCount被赋值。 (That value is the output of calling the built-in parseInt() function, using whatever is inside the counterDiv element as the input. (该值是调用内置parseInt() function 的 output,使用counterDiv元素内的任何内容作为输入。
  3. newCount is assigned a value. newCount被赋值。 (That value is one more than the value in oldCount .) (该值比oldCount中的值大一。)
  4. Whatever is inside the counterDiv element is replaced with the value stored in newCount . counterDiv元素中的任何内容都将替换为存储在newCount中的值。

 // Defines references to elements (using `const` because the values // should never change) const clickableDiv = document.getElementById("clickableDiv"); const counterDiv = document.getElementById("counterDiv"); // Defines a listener that will call our function whenever a click happens document.addEventListener("click", count); // Defines the `count` function function count(event){ // Limits which click events will change our counter if (event.target == clickableDiv){ // Declares variables to hold numbers (using `let` in case we // might want to change the values later) let oldCount; let newCount; // Assumes the HTML content of counterDiv looks like a number, // gets that number, and stores it in oldCount oldCount = parseInt(counterDiv.innerHTML); // Adds 1 to the number stored in oldCount, and stores the result // in newCount newCount = oldCount + 1; // Makes a string from the number (not strictly necessary) // and replaces the HTML content of counterDiv with that string counterDiv.innerHTML = newCount.toString(); } }
 div { float: left; width: 25%; height: 2em; padding: 1em; text-align: center; font-weight: bold; border: 1px solid grey; }
 <div id=clickableDiv>Click me</div> <div id="counterDiv">0</div>

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

相关问题 如何在单击其他元素时显示元素? - How do I show an element when another element has already been clicked? 如何获得已单击的Div的名称? - How do I get the name of a Div that has been clicked? 我如何获得一个按钮来执行多项任务,具体取决于单击了多少次? (JavaScript) - How can i get one button to do multiple tasks depending on how many times it has been clicked? (Javascript) 如何获得一个按钮被单击的次数的变量,将其在线存储然后在以后访问? - How do I get a variable of the number of times a button has been clicked, store it online and then access it later? 单击添加按钮后如何显示应答按钮? - How to show answer buttons after add button has been clicked on? 我如何计算一个组件被称为Angular 4的次数 - How do i count how many times a component has been called Angular 4 如果连续两次单击某个元素,则隐藏div,否则显示 - Hide a div if an element has been clicked twice in a row, else Show 如何根据在 React 中单击哪个按钮来切换 div class? - How do I toggle div class depending on which button has been clicked in React? 单击div时如何切换 - How to toggle when a div has been clicked jQuery根据单击按钮的次数更改元素 - jQuery changing elements depending on how many times the button has been clicked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM