简体   繁体   中英

How do I use a button to count through an array using JavaScript?

How do I use a button to count through an array using JavaScript?

My code :

 var dataset = ["A", "B", "C", "D", "E"]; var counter = 0; function onClick() { counter++; }; document.write(dataset[counter]);
 <button type="button" onClick="onClick()">Click me</button>

I want to print "A" first, and then "B" when the button is clicked, and so on.

My current code isn't working. How can I fix the code to achieve this?

You need a target element for the output, because if the page is finished, you create then a new HTML document.

Please have a look here: Why is document.write considered a "bad practice"?

 function onClick() { if (counter < dataset.length) { document.getElementById('output').innerHTML += dataset[counter++] + ' '; } }; var dataset = [ "A" , "B" , "C" , "D" , "E" ], counter = 0; 
 <button type="button" onClick="onClick()">Click me</button> <div id="output"></div> 

You should write it inside onClick() function. So that whenever the user clicks the button, onClick() function gets invoked and changes the value in the element using innerHTML property.

It's best practice to create a element separately and change its value instead of using document.write .

 var dataset = ["A", "B", "C", "D", "E"]; var counter = 0; function onClick() { const para = document.getElementById('para'); para.innerHTML = dataset[counter]; if(counter < (dataset.length-1)) { counter++; } else { counter = 0; } }; 
 <button type="button" onClick="onClick()">Click me</button> <p id="para"></p> 

Your script at the bottom will only run once when the page loads, so it doesn't have any idea that counter is changing. Instead, you can add the document write to your onClick method.

Also, at the moment you are appending your letter to the body, replacing everything that was there before, including the button. Instead, you can create a div which will hold the resulting letter pulled from your array.

Moreover, I suggest you use counter % dataset.length so that your letter wraps around each time you reach the end of your array:

 <script type="text/javascript"> var dataset = ["A", "B", "C", "D", "E"]; var counter = 0; function onClick() { document.getElementById("res").textContent = (dataset[counter % dataset.length]); counter++; }; </script> <button type="button" onClick="onClick()">Click me</button> <div id="res"></div> 

This will help you

  var dataset = ["A", "B", "C", "D", "E"]; var counter = 0; function onClick() { document.getElementById("in").innerHTML = dataset[counter]; counter++; if(counter == dataset.length) counter = 0; }; 
 <button type="button" onClick="onClick()">Click me</button> <p id ="in"></p> 

You can have a div and target it onClick and add value from dataset to it using innerHTML

 <script type="text/javascript"> var dataset = [ "A" , "B" , "C" , "D" , "E" ]; var counter = 0; function onClick() { document.getElementById('data').innerHTML = dataset[counter] counter++; counter = counter % 5 }; </script> <button type="button" onClick="onClick()">Click me</button> <div id='data'></div> 

 var dataset = ["A", "B", "C", "D", "E"]; var counter = 0; function onClick() { /* If you want the previous result to be removed and new result to appear use the below code*/ /*document.getElementById("result").innerHTML =dataset[counter]; */ /* Or if you want to append the result, retaining the previous result use this */ document.getElementById("result").innerHTML+=(dataset[counter] + ", "); counter++; if(counter == 5){ counter = 0; } }; 
 <button type="button" onClick="onClick()">Click me</button> <div id='result'></div> 

The code executed on click is:

function onClick() {
  counter++;
}

As you can see, the counter is incremented but the screen is not refreshed. To fix this problem you could think of copying document.write(counter) inside the function, but the first time the button is clicked document.write overwrites the original HTML and the button disappears:

 counter = 0; document.write(counter); function onClick() { counter++; document.write(counter); } 
 <button onclick="onClick()">increase</button> 

To refresh the screen properly you need to know what the DOM is. Roughly speaking, the DOM (Document Object Model) is an equivalent of your HTML document in the JavaScript world. Thanks to the DOM you can manipulate the HTML document using JavaScript.

Think of an HTML document as a tree with parent and child elements (for example <html> has two children, <head> and <body> ). The root of this tree is the document itself, and the first child of the document is the <html> element. In the JavaScript world, the document can be found in a preexisting variable called document . You can ask document to find some descendant elements for you like so:

html = document.children[0];
buttons = document.getElementsByTagName("button");

You can also manipulate the elements one by one. For example, if you want to change the text inside the button, you can do it like so:

button = buttons[0]; // first button found in the tree
button.textContent = "counter plus plus";

Based on this knowledge, here is a possible solution to print the counter on click:

 counter = 0; function onClick() { counter++; var span = document.getElementById("counter"); span.textContent = counter; } 
 <button onclick="onClick()">increment</button> <span id="counter">0</span> 

I suppose you can finish the job by yourself :-)

The Code provided does not update HTML on every click and hence the UI is not update on button action. It should be somewhat like

function onClick() {
 //all updation goes here
 counter++;
 document.write(dataset[counter]);
};

In case you don't want to update entire HTML which document.write does then attach a ID or class to it and update only that element on each button click action

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