1、问题背景
利用select2生成可搜索下拉框,并且绑定切换事件;但是直接绑定change事件,发现不起作用
2、问题原因
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>select2切换事件</title>
<link rel="stylesheet" href="../css/select2.css" />
<script src="../js/jquery-3.2.1.js"></script>
<script src="../js/select2.js"></script>
<script>
$(function(){
$("#selData").select2();
$("#selData").off().on("change",function(){
var data = $(this).val();
alert(data);
});
});
</script>
</head>
<body>
<div>
<select id="selData" class="js-example-basic-single" style="300px;">
<option value=""></option>
<option value="1">李四</option>
<option value="2">王武</option>
<option value="3">华章</option>
<option value="4">司徒</option>
<option value="5">朝华</option>
<option value="6">沈磊</option>
</select>
</div>
</body>
</html>
上述代码,下拉搜索框切换事件直接使用change,发现选中的值不能回填到框中3、解决办法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>select2切换事件</title>
<link rel="stylesheet" href="../css/select2.css" />
<script src="../js/jquery-3.2.1.js"></script>
<script src="../js/select2.js"></script>
<script>
$(function(){
$("#selData").select2();
$("#selData").on("select2:select",function(){
var data = $(this).val();
alert(data);
});
});
</script>
</head>
<body>
<div>
<select id="selData" class="js-example-basic-single" style="300px;">
<option value=""></option>
<option value="1">李四</option>
<option value="2">王武</option>
<option value="3">华章</option>
<option value="4">司徒</option>
<option value="5">朝华</option>
<option value="6">沈磊</option>
</select>
</div>
</body>
</html>
将change换成select2:select,这样下拉搜索框可以回填值了