Select2 event that triggers on any option, selected or not selected?

我的未来我决定 提交于 2019-12-14 03:10:49

问题


Click on 1, 2, 3 in the snippet below. How can I reach originalEvent so the alert open up on the already selected item, the same way as the other options in the list?

I've tried the built in events, but I can't seem to find one that triggers on any select in the list, already selected or not.

$(".form-control").select2({
  templateResult: formatSelect2,
});

$(".form-control").on('select2:select', function (evt) {
	var origEvent = evt.params.originalEvent;
	    if($(origEvent.target).closest('.statuses span').length) {
      var data = $(origEvent.target).parents('li[aria-selected]').data('data').text || null; 
      alert('Clicked \"' + $(origEvent.target).html() + '\" from the value: ' + data);	
    }
});

function formatSelect2 (data) {
  if (!data.id) { return data.text; }
  var $data = $(
    '<span data-status="' + data.element.getAttribute("data-status") + '">' + data.text + '<span class="statuses"><span data-status="1">1</span><span data-status="2">2</span><span data-status="3">3</span></span></span>'
  );
  return $data;
}
.statuses {
  margin-left: 8px;
}
.statuses span {
  margin-left: 8px;
  cursor: pointer;
}
.statuses span:hover {
  margin-left: 8px;
  color: red;
}
<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/4.0.5/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
<select class="form-control render_select2" style="width: 300px">
  <option selected="selected" data-status="1">orange</option>
  <option>white</option>
  <option>purple</option>
</select>

<select class="form-control render_select2" style="width: 300px">
  <option selected="selected" data-status="1">orange1</option>
  <option>white1</option>
  <option>purple1</option>
</select>

来源:https://stackoverflow.com/questions/51994554/select2-event-that-triggers-on-any-option-selected-or-not-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!