是否可以在response
事件和渲染项实现中设置if语句?我有两个json文件,并在#searchbox
和中使用数据属性.searchbar
来获取url。由于文件对象不同,我想我需要使用两个不同的响应和标记。我可以设置开关语句还是以下语句?我的代码出现某种未定义的错误。
Uncaught TypeError: undefined is not a function jquery.js:9597
我可以看到返回了json文件,但是没有显示自动完成功能。有什么建议?
的HTML
<input type='text' data-search="jsonfileA" id="searchbox">
<input type='text' data-search="jsonfileB" class="searchbar">
代码:
$( "#searchbox,.searchbar" ).each(function(){
var search = $(this).data('search');
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url: search,
dataType:"json",
data:{q:request.term},
success: function( data ) {
response($.map(data.products, function( item)
{
if ($(this).is('#searchbox')) {
return {
label:item.name,
category:item.category
}
}else {
return {
title:item.title,
description:item.description
}
}
});
)};
});
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
var inner_html;
if ($(this).is('#searchbox')) {
inner_html = ''+item.label+'<p>'+item.category+'';
}
else {
inner_html = ''+item.title+'<p>'+item.description+'';
}
return $("<li></li>")
.data("item.autocomplete", item)
.append(inner_html)
.appendTo(ul);
};
});
var $this = $(this)
在.each
函数内部声明,然后用于在和函数中$this
引用自动完成功能。input
.each
.ajax
$( "#searchbox,.searchbar" ).each(function(){
var $this = $(this), // declared here
search = $this.data('search'); // used here
$this.autocomplete({ // used here
source: function( request, response ) {
$.ajax({
url: search,
dataType:"json",
data:{q:request.term},
success: function( data ) {
response($.map(data.products, function( item)
{
if ($this.is('#searchbox')) { // used here
return {
label:item.name,
category:item.category
}
} else {
// rest of your code - replace any remaining references to the autocomplete input with $this
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句