如何用document.getElementById及按钮点击在HTML中显示JavaScript数组元素
Hey Matthijs, let's fix up your code and tackle both of your questions step by step.
Issues in Your Current Code
First, let's spot the small problems holding your code back:
- The
cijfer1function has an unusedJavaScriptparameter that doesn't serve any purpose here. document.getElementById("cijfer1").innerHTML = [1];is setting the span to show a literal array[1], not pulling values from yourcijfersarray.- Quick reminder: Array indices start at 0, so
cijfers[0]is the first element ("6.9"),cijfers[1]is the second ("7.2"), and so on.
1. Insert Array Values into HTML with document.getElementById
To plug values from your cijfers array into the HTML element with ID cijfer1, you just need to target that element and assign the desired array element to its innerHTML property.
Basic Example: Show a Specific Array Element on Button Click
Here's the corrected code for your initial goal (showing the second element in the array when the button is clicked):
<span id="cijfer1"></span> <br> <button onclick="cijfer1()">Cijfer</button>
var cijfers = ["6.9", "7.2", "8.3", "8.2", "7.4", "7.8", "8.2", "7"]; function cijfer1() { // Target the span and set its content to the 2nd array element (index 1) document.getElementById("cijfer1").innerHTML = cijfers[1]; }
2. Show Array Elements on Button Click (Extended Options)
If you want more flexibility than just showing one element, here are two common, useful variations:
Option A: Show All Array Elements at Once
If you want to display the entire array as a clean, comma-separated list when the button is clicked:
var cijfers = ["6.9", "7.2", "8.3", "8.2", "7.4", "7.8", "8.2", "7"]; function cijfer1() { // Join array elements into a readable string var allCijfers = cijfers.join(", "); document.getElementById("cijfer1").innerHTML = allCijfers; }
This will display: 6.9, 7.2, 8.3, 8.2, 7.4, 7.8, 8.2, 7 after clicking the button.
Option B: Cycle Through Elements on Each Click
If you want to show a new element every time you click the button (looping back to the start once you reach the end):
var cijfers = ["6.9", "7.2", "8.3", "8.2", "7.4", "7.8", "8.2", "7"]; // Track which element we're currently showing var currentIndex = 0; function cijfer1() { // Update the span with the current array element document.getElementById("cijfer1").innerHTML = cijfers[currentIndex]; // Move to the next element, reset to 0 if we hit the end of the array currentIndex = (currentIndex + 1) % cijfers.length; }
Now each click will cycle through your grades, looping back to "6.9" after showing the last element ("7").
Key Takeaways
- Use
document.getElementById("your-element-id")to target the HTML element you want to update. - Access array elements with
arrayName[index](don't forget indices start at 0!). - Use
innerHTMLto set the content of the target element to your desired value.
内容的提问来源于stack exchange,提问作者Matthijs Hulshof

