jQuery / Select2 即使选择了某个值也会触发

jQuery / Select2 trigger even when certain value selected

我正在使用 Select2 作为下拉菜单,我想做的是当从下拉菜单中选择某个值时触发事件(例如警报)

我已经尝试过以下方法,但没有成功:

$(".js-dropdown").val(2)(function() {
  console.log("val2 selected")
});

$(function() {
  $('select').select2()
    .val("2", function(e) {
      console.log("value changed");
    })
});

我做错了什么?


我的选择2:

$(".js-dropdown").select2({
  placeholder: "Text",
  allowClear: false,
  closeOnSelect: false
});

Codepen

如果所选值为 2

,则绑定 change event 处理程序并调用函数

var $sel = $(".js-dropdown");
$sel.select2({
  placeholder: "Text",
  allowClear: false,
  closeOnSelect: false
});

$sel.change(function() {
  if (this.value == 2)
    alert('2')
})
body {
  font-family: helvetica;
  font-weight: bold
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>
<select class="js-dropdown" style="width: 220px;">
  <option></option>
  <option value="1">Dropdown-1</option>
  <option value="2">Dropdown-2</option>
  <option value="3">Dropdown-3</option>
  <option value="4">Dropdown-4</option>
  <option value="5">Dropdown-5</option>
  <option value="6">Dropdown-6</option>
  <option value="7">Dropdown-7</option>
</select>