从 jQuery UI Slider 获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5307325/
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 the value from a jQuery UI Slider
提问by AKor
I have a jQuery UI slider that is part of a rating system. You slide to values 1 - 5 in order to rate it 1 thru 5. I have it defaulted to 3 when the slider first appears. The form that it is part of has a hidden input whose value should be the value of the slider, but it is not.
我有一个 jQuery UI 滑块,它是评分系统的一部分。您滑动到值 1 - 5 以将其评分为 1 到 5。当滑块第一次出现时,我将其默认为 3。它所属的表单有一个隐藏输入,其值应该是滑块的值,但它不是。
Here's the jQuery:
这是jQuery:
$( "#ratingSlider" ).slider({
range: "min",
value: 3,
min: 1,
max: 5,
slide: function( event, ui ) {
$( "#ratingResult" ).val( ui.value );
}
});
$( "#ratingResult" ).val( $( "#ratingSlider" ).slider( "value" ) );
$("#ratingSlider").change(function(){
$( "#rateToPost" ).attr('value', $( "#ratingSlider" ).slider( "value" ) );
});
I tried making the .val() of #rateToPost to be the .val() of the slider, but it always only gave it 3 (the default value).
我尝试将#rateToPost 的 .val() 设为滑块的 .val(),但它始终只给它 3(默认值)。
How can I make it pass the value properly?
我怎样才能让它正确传递值?
Also, I want to have the value automatically refresh (right now it is displayed using a text box but I really don't want to use a text box) on the page whenever the slider is moved, how can I do that?
另外,我想在移动滑块时自动刷新页面上的值(现在它使用文本框显示,但我真的不想使用文本框),我该怎么做?
回答by Michal
To display rating as you slide in your slider initialization you need to change the text of that div (Assuming you have a div (not an input box) with an id "ratingResult"). To update the value when user finishes dragging you need to add the change event to the initialization code.
要在滑块初始化中滑动时显示评分,您需要更改该 div 的文本(假设您有一个 ID 为“ratingResult”的 div(不是输入框))。要在用户完成拖动时更新值,您需要将更改事件添加到初始化代码中。
$("#ratingSlider").slider({
range: "min",
value: 3,
min: 1,
max: 5,
//this gets a live reading of the value and prints it on the page
slide: function(event, ui) {
$("#ratingResult").text(ui.value);
},
//this updates the value of your hidden field when user stops dragging
change: function(event, ui) {
$('#rateToPost').attr('value', ui.value);
}
});
回答by Richard Poole
Use ui.value
in the change event handler.
使用ui.value
在变化的事件处理程序。
$('#ratingSlider').change(function(e, ui) {
$('#rateToPost').attr('value', ui.value);
});