我有一个滑块(输入类型范围),它应该在更改值时运行一个函数.然后该函数应在单独的 div 容器中显示新值.在函数中放置警报后,我知道该函数没有被调用,但是在谷歌搜索了一个小时并尝试了几种不同的方法后,我找不到错误.
I have a slider (input type range) that is supposed to run a function when the value is being changed. The function should then display the new value in a separate div container. After placing an alert in the function, I know that the function isn't being called, but after googling for an hour and trying a few different methods I just can't find the error.
这是 HTML 部分:
Here's the HTML part:
<input id="slide" type="range" min="1" max="100" step="1" value="10" onchange="updateSlider(this.value)">
<div id="sliderAmount"></div>
JavaScript:
JavaScript:
// Slider
function updateSlider(slideAmount)
{
alert("error");
var sliderDiv = document.getElementById("sliderAmount");
sliderDiv.innerHTML = slideAmount;
}
可以,你只需要确保在渲染元素时定义了JavaScript函数,例如:
It works, you just need to make sure that the JavaScript function is defined when the element is rendered, for example:
<script>
function updateSlider(slideAmount) {
var sliderDiv = document.getElementById("sliderAmount");
sliderDiv.innerHTML = slideAmount;
}
</script>
<input id="slide" type="range" min="1" max="100" step="1" value="10" onchange="updateSlider(this.value)">
<div id="sliderAmount"></div>
查看此演示:https://jsfiddle.net/Mmgxg/
更好的方法是删除内联 onchange
属性:
A better way would be to remove the inline onchange
attribute:
<input id="slide" type="range" min="1" max="100" step="1" value="10">
<div id="sliderAmount"></div>
然后在你的 JavaScript 代码中添加监听器:
And then add the listener in your JavaScript code:
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
}
https://jsfiddle.net/PPBUJ/
这篇关于具有 onchange 功能的 HTML5 滑块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!