如何在select2上调用onclick事件

Azi*_*ima 4 javascript jquery onclick jquery-select2

我正在尝试绑定 onclick 以选择带有 select2 初始化的输入元素。

我想在单击或聚焦下拉列表时绑定处理程序。

<select class="form-control" id="type" name="type" required="required">
    <option value="breakfast" <?= ($type == 'breakfast')? 'selected' : '';?>>Breakfast</option>
    <option value="snacks" <?= ($type == 'snacks')? 'selected' : '';?>>Snacks</option>
</select>
Run Code Online (Sandbox Code Playgroud)

这是js部分:

$('#type').select2({}).on("select2-selecting", function(e) {
    console.log('not working');
});
Run Code Online (Sandbox Code Playgroud)

我也试过“ select2-open/opening”但无济于事。如何使事件绑定工作?

Zak*_*rki 5

在您使用的 3.5.1 版本中,您应该使用select2-selecting而不是select2:selectinglike :

$('#type').select2({}).on("select2-selecting", function(e) {
    console.log('not working');
});
Run Code Online (Sandbox Code Playgroud)

$('#type').select2({}).on("select2-selecting", function(e) {
    console.log('not working');
});
Run Code Online (Sandbox Code Playgroud)
$('#type').select2({});

$('#type').on("select2-opening", function(e) {
  console.log('Opening');
});
$('#type').on("select2-selecting", function(e) {
  console.log('Selecting');
});
Run Code Online (Sandbox Code Playgroud)