javascript 从范围输入(滑块)中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19716398/
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
Getting value from a range input (slider)
提问by MightyMouse
I am adding a slider dynamically on a page using a string like the one below:
我正在使用如下所示的字符串在页面上动态添加滑块:
"<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>";
Then, after I append it to the page using plain javascript I can delegate using the following code:
然后,在我使用普通的 javascript 将它附加到页面后,我可以使用以下代码进行委托:
$('input[name=aName]').on('change', function () { alert(this.value)});
and indeed when the value changes, I receive the alert with the correct value. However, if I delegate like this:
事实上,当值发生变化时,我会收到带有正确值的警报。但是,如果我像这样委托:
$('input[name=aName]').on('change', handleChange);
and define the function later on like this:
然后像这样定义函数:
function handleChange () {
var theValue = $('input[name=aName]').value;
alert("value: " + theValue);
}
I receive the alert with the message "value: undefined". Why is this thing happening?
我收到带有消息“值:未定义”的警报。为什么会发生这件事?
回答by Krishna
This is wrong $('input[name=aName]').value
. I think you're mixing javascript & jquery.
这是错误的$('input[name=aName]').value
。我认为您正在混合使用 javascript 和 jquery。
For getting the value, use like this.
为了获得价值,像这样使用。
$('input[name=aName]').val()