我遇到了JQuery Autocompete renderItem的问题。我的自动填充功能正常,但似乎在收到数据后未调用.data("ui-autocomplete")._renderItem
。运行脚本时,我没有收到任何错误。我尝试console.log("success");
,但它既不会运行。我错过了什么吗? jquery-ui上的版本是1.12.1。任何帮助将不胜感激!
HTML:
<td class="itemCodeHd"><input class="itemCode" name="ItemCode[]" <?php echo "value='$ItemCode'"?> <?php echo "id= ItemCodeItem" . $l;?> ></td>
<td class="itemDescriptionSalesHd"><textarea class="itemDescriptionSales" name="ItemDescriptionSales[]" <?php echo "id= ItemDescriptionSalesItem" . $l;?> rows="1" tabindex="2"><?php echo "$ItemDescriptionSales"?></textarea></td>
JSON:
[{"itemCode":"001","itemDescriptionSales":"Item 1"},
{"itemCode":"002","itemDescriptionSales":"Item 2"},
{"itemCode":"003","itemDescriptionSales":"Item 1"}]
Jquery:
$( function() {
$( ".itemCode" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "item-search.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
} );
},
minLength: 3,
select: function( event, ui ) {
$(this).parent().siblings().children(".itemDescriptionSales").val(ui.item.itemDescriptionSales);
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
console.log("success");
return $('<li>')
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.itemCode + "<br>" + item.itemDescriptionSales + "</a>" )
.appendTo( ul );
};
} );
答案 0 :(得分:1)
好。我不能在没有php的情况下测试这个,但我认为正在发生的是console.log()
根本没有触发的代码,因为它在一个单独的函数中。尝试将此代码移动到ajax调用的success函数中。类似于我在下面所做的事情。警告......未经测试的代码!
$( function() {
$( ".itemCode" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: "item-search.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data ).data("ui-autocomplete")._renderItem = function (ul, item) {
console.log("success");
return $('<li>')
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.itemCode + "<br>" + item.itemDescriptionSales + "</a>" )
.appendTo( ul );
};
}
} );
},
minLength: 3,
select: function( event, ui ) {
$(this).parent().siblings().children(".itemDescriptionSales").val(ui.item.itemDescriptionSales);
}
})
});