我正在尝试在 slider 中动态设置最大值,最大值是从输入 #max 获取的,我尝试 $("#max").val 将此代码放入 max 变量中,但它不是正在工作。
编辑: 当用户选择一个类别时,我显示该类别中的所有产品,并使用ajax部分将值设置为输入#max(最高价格)
//When user select one category, I display all the product from this category, and in my ajax part I
$('#category').change(function () {
$.ajax({
url: 'ajax.php',
data: {category: category},
dataType: 'json',
cache: false,
type: "GET",
success: function(data){
if (data.length > 0) {
data.forEach(function (elem) {
$('#max').val(elem.MaxPrice); //set the Maximum price in the hidden input
$('#listing_annonce_int').append('<div id="title">'+ elem.title +'</div><div id="price">'+ elem.price +'</div>');
})
}
}
})
});
/**************************************/
function showProducts(minPrice, maxPrice) {
$("#listing_annonce_int .listing_annonce_view").hide().filter(function() {
var price = parseInt($(this).data("price"), 10);
return price >= minPrice && price <= maxPrice;
}).show();
}
$(function() {
var options = {
range: true,
min: 0,
max: 20000,
values: [0, 5000],
slide: function(event, ui) {
var min = ui.values[0],
max = ui.values[1];
$("#amount").val(min + " € - " + max + " €");
showProducts(min, max);
}
}, min, max;
$("#slider-range").slider(options);
min = $("#slider-range").slider("values", 0);
max = $("#slider-range").slider("values", 1);
$("#amount").val( min + " €- " + max + " €");
showProducts(min, max);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<select id="category" name="category">
<option value='1'>cat 1</option>
<option value='2'>cat 2</option>
</select>
<input type="text" id="amount"/>
<input type="text" id="max"/>
<div id="slider-range"></div>
最佳答案
这是因为您没有执行任何操作来设置新值。您需要添加此监听器:
$('#max').keyup(function(){
$( "#slider-range" ).slider( "option", "max", parseInt($(this).val()) );
});
您还应该查看该功能的文档:http://api.jqueryui.com/slider/#option-max
工作 fiddle :https://jsfiddle.net/4p2mL282/1/
更新答案
你真的需要输入框吗?最简单的方法就是直接改。替换
$('#max').val(elem.MaxPrice);
与
$( "#slider-range" ).slider( "option", "max", parseInt(elem.MaxPrice));
在change()函数的AJAX调用中
如果您需要输入框,我可以解释为什么您当前的版本无法工作。当您使用 .val()
更改具有 onchange-listener 的元素的值时,您始终必须自行触发该事件。
即对于您在评论中的示例
$('#max').val('1000').change();
您始终可以通过调用函数而不传递任何参数来强制事件。
但这仍然不是你正确的问题。您的问题是,您正在 #category 的更改函数中设置 #max 字段的值,但您没有 #max 的任何更改监听器。
我强烈建议您使用我首先提供更新答案的简单方法。
关于javascript - 动态设置 slider 的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30577293/