我使用Chosen jQuery插件,但我注意到 max_selected_options 无法正常工作:
代码是这样的:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="chosen/chosen.css" />
</head>
<body>
<select id="assets" data-placeholder="Choose assets" class="chzn-select" multiple style="width:350px;" tabindex="4">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
<option value="g">g</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="chosen/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({allow_single_deselect:true});
$('.chzn-select').chosen({ max_selected_options: 3 });
$(".chzn-select").bind("liszt:maxselected", function () { alert("a"); });
$(".chzn-select").chosen().change( function () { alert("a"); } );
});
</script>
</body>
</html>
我不明白我的代码有什么不对。这行:
$('.chzn-select').chosen({ max_selected_options: 3 });
应该限制允许选择的最大数量。但这是行不通的。我仍然可以选择任意数量的项目。
我注意到,在达到所选项目的最大数量的情况下,应该触发的事件也不会触发:
$(".chzn-select").bind("liszt:maxselected", function () { alert("a"); });
我的代码有错误吗?
还有一个问题:如何将搜索功能添加到列表中,例如出现在插件页面上第一个示例中的搜索框?
谢谢。
最佳答案
您两次调用chosen()
方法,这就是您遇到问题的原因:
$(".chzn-select").chosen();
$('.chzn-select').chosen({ max_selected_options: 3 });
删除第一个,它可以工作。您的JS代码应为:
$(document).ready(function(){
$(".chzn-select-deselect").chosen({allow_single_deselect:true});
$(".chzn-select").chosen({ max_selected_options: 3 });
$(".chzn-select").bind("chosen:maxselected", function () { alert("max elements selected"); });
$(".chzn-select").chosen().change( function () { alert("change"); } );
});
关于jquery-plugins - 选择插件max_selected_options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382875/