Javascript 具有 onchange 功能的 HTML5 滑块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13896685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 Slider with onchange function
提问by Necroteuch
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 seperate 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.
我有一个滑块(输入类型范围),它应该在更改值时运行一个函数。然后该函数应在单独的 div 容器中显示新值。在函数中放置警报后,我知道该函数没有被调用,但是在谷歌搜索一个小时并尝试了几种不同的方法后,我只是找不到错误。
Here's the HTML-part:
这是 HTML 部分:
<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;
}
Thanks in advance!
提前致谢!
回答by David Hellsing
It works, you just need to make sure that the javascript function is defined when the element is rendered, f.ex.
它有效,您只需要确保在呈现元素时定义了 javascript 函数,f.ex。
<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>?
See this demo: http://jsfiddle.net/Mmgxg/
看这个演示:http: //jsfiddle.net/Mmgxg/
A better way would be to remove the inline onchangeattribute:
更好的方法是删除 inlineonchange属性:
<input id="slide" type="range" min="1" max="100" step="1" value="10">
<div id="sliderAmount"></div>
And then add the listener in your javascript:
然后在你的 javascript 中添加监听器:
var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");
slide.onchange = function() {
sliderDiv.innerHTML = this.value;
}?

