JQuery和select2选择器引用

时间:2017-12-28 02:35:17

标签: jquery reference jquery-select2

假设我有一个对象,其设置具有对元素的id引用,如下所示:

(function (Erasmus, $, undefined) {
    var settings = {
        Agreement : {
            SourceUniversity: "#scrUni",
        }
    };
    Erasmus.Settings = settings;
})(window.Erasmus = window.Erasmus || {}, jQuery);

现在所有的选择输入都是select2,在初始化完所有内容后,我将输入的变更事件绑定到这样:

(function (Erasmus, $, undefined) {
    var student = {
        BindPageControls: function () {
            $(Erasmus.Settings.Agreement.SourceUniversity).on("select2:select", function (selected) {
               console.log(selected); 
        });
      }
    };
    Erasmus.Student = student;
})(window.Erasmus = window.Erasmus || {}, jQuery);

现在的问题是,如果我绑定:

$(Erasmus.Settings.Agreement.SourceUniversity).on(...

它绑定到另一个对象(原始输入?)而不是select2输入并且不会触发事件,但是如果我像这样绑定:

$("#srcUni").on(...

一切正常。为什么在将纯字符串和字符串作为变量传递时,JQuery会获取不同的引用?

JQuery版本3.2.1,select2版本4.0.4

1 个答案:

答案 0 :(得分:0)

以下是您的代码中的一个工作示例:



$(document).ready(function() {
  $('#srcUni').select2({
      placeholder: 'Select an option',
      width: 'resolve',
    	dropdownAutoWidth: 'true',
    	allowClear: 'true',
  });

  Erasmus.Student.BindPageControls();
});

(function (Erasmus, $, undefined) {
    var settings = {
        Agreement : {
            SourceUniversity: "#srcUni",
        }
    };
    Erasmus.Settings = settings;
})(window.Erasmus = window.Erasmus || {}, jQuery);

(function (Erasmus, $, undefined) {
    var student = {
        BindPageControls: function () {
            $(Erasmus.Settings.Agreement.SourceUniversity).on("select2:select", function (e) {
            var data = e.params.data;
            console.log("select item: ",data); 
        });
      }
    };
    Erasmus.Student = student;
})(window.Erasmus = window.Erasmus || {}, jQuery);

select {
  width: 200px
}

<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.full.min.js"></script>

<select id="srcUni">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
&#13;
&#13;
&#13;