JQuery和select2选择器引用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
答案
以下是您的代码中的一个工作示例:
$(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>
以上是关于JQuery和select2选择器引用的主要内容,如果未能解决你的问题,请参考以下文章