如何在JavaScript中获取范围滑块的值?现有代码无法弹出值求协助
Hey there! Let's break down why your calculate function isn't working and get it sorted out quickly.
The Root Problem
Looking at your HTML, your range inputs have a name attribute (like name="size") but no id attribute. When you try document.getElementById("size"), the browser can't find the element because it's searching for an element with id="size", not name="size". That's why your alert doesn't pop up with the value.
Quick Fixes
Here are a few ways to get the slider values working, depending on your preference:
1. Add id Attributes (Simplest for Your Existing Code)
Just add id attributes to your range inputs to match what your calculate function is looking for:
<p> <label for="range_size">Size: </label> <input type="range" name="size" id="size" class="slider" min="1" max="75" value="45"> <span class="slider_label"></span> </p> <p> <label for="range_width">Width: </label> <input type="range" name="width" id="width" class="slider" min="1" max="6" value="1"> <span class="slider_label"></span> </p>
Then fix your calculate function to close properly, and it will work:
function calculate() { var size = document.getElementById("size").value; alert(size); }
2. Use the name Attribute to Fetch Values
If you don't want to add ids, you can use getElementsByName (note this returns a collection, so we grab the first element):
function calculate() { var size = document.getElementsByName("size")[0].value; var width = document.getElementsByName("width")[0].value; alert(`Size: ${size}, Width: ${width}`); }
3. Use jQuery (Since You're Already Using It)
Since your existing code uses jQuery, you can simplify value retrieval with it:
function calculate() { var size = $('input[name="size"]').val(); var width = $('input[name="width"]').val(); alert(`Size: ${size}, Width: ${width}`); }
Bonus: Clean Up Your Existing Slider Update Code
Your current jQuery code to update the labels works, but we can make it a bit cleaner and more reliable:
$(function() { // Update label when slider changes $('.slider').on('input change', function(){ $(this).next('.slider_label').text(this.value); }); // Set initial label values $('.slider_label').each(function(){ var value = $(this).prev('.slider').val(); // Use .val() instead of .attr('value') to get live values $(this).text(value); }); });
Using .val() instead of .attr('value') ensures you get the current live value of the input, not just the initial value set in the HTML.
内容的提问来源于stack exchange,提问作者alphal

