您只需要选择句柄元素而不是 Phill 在他的 JSFiddle 中选择的那个:
$("#slider").change(function() {
var sVal = $(this).val(),
$ele = $(this).next().children();
if(sVal > 21 && sVal <= 40) {
$ele.addClass('skull-class').removeClass('envelope-class coffee-class beermug-class');
}
if(sVal > 41 && sVal <= 60) {
$ele.addClass('envelope-class').removeClass('skull-class coffee-class beermug-class');
}
if(sVal > 61 && sVal <= 80) {
$ele.addClass('coffee-class').removeClass('envelope-class skull-class beermug-class');
}
if(sVal > 81 && sVal <= 100) {
$ele.addClass('beermug-class').removeClass('envelope-class coffee-class skull-class');
}
});
这是一个演示:http: //jsfiddle.net/jasper/YgJ9P/192/
我没有使用.css()
给元素添加样式,而是设置了一些类来保持我的 JS 代码和我的 CSS 代码分开:
.ui-slider .skull-class {
background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/21-skull.png);
}
.ui-slider .envelope-class {
background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/18-envelope.png);
}
.ui-slider .coffee-class {
background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/100-coffee.png);
}
.ui-slider .beermug-class {
background : url(http://jquerymobile.com/demos/1.0b2/docs/toolbars/glyphish-icons/88-beermug.png);
}
你也可以稍微压缩一下JS:
var allClasses = 'skull-class envelope-class coffee-class beermug-class';
$("#slider").change(function() {
//get the value of the slider as well as cache the slider handle element
var sVal = $(this).val(),
$ele = $(this).next().children();
//remove the icon classes from the handle
$ele.removeClass(allClasses);
(sVal > 21 && sVal <= 40) ? $ele.addClass('skull-class') :
(sVal > 41 && sVal <= 60) ? $ele.addClass('envelope-class') :
(sVal > 61 && sVal <= 80) ? $ele.addClass('coffee-class') :
(sVal > 81 && sVal <= 100) ? $ele.addClass('beermug-class') : ''
});
http://jsfiddle.net/jasper/YgJ9P/195/