簡體   English   中英

Select2 下拉更改事件不起作用

[英]Select2 drop down change event not working

我正在使用Select2下拉菜單,我需要根據下拉菜單選擇執行一些功能。

我嘗試了以下代碼,但它對我不起作用。

$eventSelect.on("select2:select", function (e) { log("select2:select", e); });

$eventSelect.on("change", function (e) { log("change"); });

誰能告訴我怎樣才能使這項工作?

我正在使用select2版本3.3.2 ,以下代碼對我有用

$("#id").on("change", function () { debugger; });

您可以在知道網頁已完全加載后嘗試聲明事件,在我的情況下,這就是問題所在:

 $(document).ready(function(){ $('#yourselect').on("select2:select", function(e) { console.log($(this).val()); }); }); 

試試這個代碼

$eventSelect.select2().on("change", function(e) {
          // mostly used event, fired to the original element when the value changes
          log("change val=" + e.val);
        })

我可以看到你從select2文檔中獲取了你的代碼:

https://select2.github.io/examples.html#programmatic-control

您是否注意到他們在下面定義了一個函數,該代碼使用了名為log()的函數。

這是功能代碼,你也包含了嗎?

function log (name, evt) {
  if (!evt) {
      var args = "{}";
  } else {
      var args = JSON.stringify(evt.params, function (key, value) {
      if (value && value.nodeName) return "[DOM node]";
      if (value instanceof $.Event) return "[$.Event]";
      return value;
      });
  }
  var $e = $("<li>" + name + " -> " + args + "</li>");
  $eventLog.append($e);
  $e.animate({ opacity: 1 }, 10000, 'linear', function () {
      $e.animate({ opacity: 0 }, 2000, 'linear', function () {
          $e.remove();
      });
    });
}

或者,您可以使用console.log()輸出到控制台。

$(document).on('change', '.js-example-basic-single', function(e) {
console.log($(this).val());})

使用 select2 版本 4,事件發生了變化。 這是一個舊版本的例子

$('#exampleVersionOld').select2().on('change', function(item){
    ...
});

這是一個新版本的例子

$('#exampleVersion4').on('select2:select', function (e) {
    var item = e.params.data;
});

請注意,項目的結構也會隨着這個新事件而改變。

這是所有新事件的列表

https://select2.org/programmatic-control/events

從版本4.0.0開始,可以使用以下事件:

參考: https://select2.org/programmatic-control/events

選擇2:關閉
選擇2:打開
select2:開場
選擇2:選擇
選擇2:刪除
選擇2:取消選擇

例如:

 (function($){ $('.select2').select2(); $('.select2').on('select2:selecting', function(e) { console.log('Selecting: ', e.params.args.data); }); })(jQuery);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script> <select class="select2"> <option>Volvo</option> <option>Saab</option> <option>Mercedes</option> <option>Audi</option> </select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM