【问题标题】:How to invoke onclick event on select2如何在 select2 上调用 onclick 事件
【发布时间】:2018-09-21 08:59:35
【问题描述】:

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

我想在单击或聚焦下拉菜单时绑定一个处理程序。

<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>

这里是js部分:

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

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

【问题讨论】:

  • 您使用的是什么版本?
  • @ZakariaAcharki 我使用的是 3.5.1 版本
  • @Harish 如果这行得通,就不会发帖了。

标签: javascript jquery onclick jquery-select2


【解决方案1】:

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

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

$('#type').select2({});

$('#type').on("select2-opening", function(e) {
  console.log('Opening');
});
$('#type').on("select2-selecting", function(e) {
  console.log('Selecting');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.1/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.1/select2.min.js"></script>
<select style="width:300px" id="type">
  <option value="CA">California</option>
  <option value="NV">Nevada</option>
  <option value="OR">Oregon</option>
  <option value="WA">Washington</option>
</select>

【讨论】:

  • 工作了..但我很确定它是select2-selecting' before I updated it to select2:selecting`..无论如何它现在正在工作..谢谢
【解决方案2】:

对于 4.0 + 版本,您可以在下面使用。

$('#yourselect').on("select2:select", function(e) { 
   // what you would like to happen
});

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2021-08-09
    • 2013-01-18
    相关资源
    最近更新 更多