如何通过单击select2元素获得输出?

时间:2018-01-11 16:27:26

标签: jquery jquery-select2

我想点击我的select2框时输出。不是我选择的东西。已经只是单击元素:



$(document).ready(

function () {
    var configParamsObj = {
        placeholder: 'Select an option...', 
        minimumResultsForSearch: 3 
    };
    $("#singleSelectExample").select2(configParamsObj);
});

$( "#singleSelectExample" ).focus(function() {
  alert( "Handler for .focus() called." );
});

$("#singleSelectExample").click(function(){
    alert("The select2 was clicked.");
}); 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<script type="text/javascript" src="http://select2.github.io/select2/select2-3.5.1/select2.js"></script>
<link rel="stylesheet" type="text/css" href="http://select2.github.io/select2/select2-3.5.1/select2.css">


<body>
  <body>Single select example
    <div class="selectRow">
        <select id="singleSelectExample">
            <option></option><!-- Needed to show X image to clear the select -->
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
            <option value="4">Option 4</option>
            <option value="5">Option 5</option>
        </select>
    </div>
</body>
  
&#13;
&#13;
&#13;

我尝试使用我的点击功能和焦点功能获得alert。但它没有用。没有输出

1 个答案:

答案 0 :(得分:1)

您可以将open / opening事件处理程序附加到Select2元素:

1)使用Select2 version 3.5

$("#singleSelectExample").on("select2-open", function(e) {
     console.log("open", e);
});

小提琴(参见Select2 3.5):https://jsfiddle.net/beaver71/wp59L8n7/

2)使用Select2 version 4.0

$("#singleSelectExample").on("select2:open", function(e) {
     console.log("open", e);
});

小提琴(适用于Select2 4.0):https://jsfiddle.net/beaver71/7bpj7asq/