Ben*_*nRH 12 html jquery jquery-select2
我正在使用Igor Vaynberg的Select2 jQuery插件和带有远程数据的无限滚动选项为我的网站制作一个自动完成搜索框.AJAX运行良好,结果显示出来,但它们是不可选择的 - 更改事件永远不会被触发,当您单击结果时,没有任何反应.
Chrome控制台中也没有出现任何错误,因此我认为这不是语法错误,而是插件将其误认为是禁用的选择框.编辑:为结果列表尝试了一个单独的点击事件,从来没有被解雇,我现在很确定有事干扰事件.
这是我目前的代码,
// Search
$("#site-search").select2({
placeholder: "Search posts",
minimumInputLength: 3,
ajax: {
url: "http://localhost/mysite/search",
dataType: 'json',
quietMillis: 500,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page // page number
};
},
results: function (data, page) {
var more = (page * 10) < data.length; // whether or not there are more results available
// return the value of more to tell if more results can be loaded
return {results: data, more: more};
}
},
formatResult: function(post) {
// return html markup for individual result item
markup = '<img src="'+post.image+'" style="width:40%;float:left;margin-right:5px">';
markup += '<p>'+post.title+'</p>';
markup += '<div class="clearfix"></div>';
return markup;
},
formatSelection: function(post) {
// This shows up in the select box
return post.title;
},
dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
}).on('change', function(e) {
try {
var slug = e.val.slug;
window.location.href = "http://localhost/mysite/posts/"+slug;
} catch(error) {
console.log('Selected search result is invalid: ');
}
});
Run Code Online (Sandbox Code Playgroud)
选择框本身只是一个输入类型为:hidden
<input type="hidden" class="bigdrop" id="site-search" style="width:100%;height:auto">
Run Code Online (Sandbox Code Playgroud)
Mur*_*rlu 47
您的问题似乎是,您的结果数据没有名为"id"的属性.Select2插件需要数据上的id字段,如果没有,则选项"不可选".您可以提供id函数来覆盖此行为:
$("#site-search").select2({
id: function(obj) {
return obj.slug; // use slug field for id
},
...
Run Code Online (Sandbox Code Playgroud)