1 回答

TA貢獻1887條經驗 獲得超5個贊
經過一些調整,我設法找到了解決方案。我保留了變量“list”,并在Typeahead的afterSelect事件中進行了調整,其中在輸入文本#products中選擇一個選項后,afterSelect事件將與所選項目相關的值發送到div #image。這個解決方案在這里可以看到有效。
下面,Ajax 和 TypeAhead 腳本進行了調整,現在也可以正常工作。調整是在 Ajax 成功和 TypeAhead afterSelect 事件中進行的:
var products;
var list = {}; // object
$ ( function ()
{
$('#categoryFK').on('change', function(){
var queryID = $(this).val();
$.ajax({
url:"fetch.php",
method:"POST",
data: {
category: queryID
},
dataType:"json",
success:function(data)
{
/* The adjust was made here on Ajax success */
console.log(data);
$("#products").val ('');
products = data;
}
});
});
$('#products').typeahead({
source: function ( query, result )
{
result ( $.map(products, function (item)
{
return item.productName;
}
));
},
/* The adjust was made here on afterSelect event */
afterSelect: function(data) {
$.each(products, function(idx, item){
list[item.productName] = item.image;
});
var img = list[data];
$('#image').html(img);
},
});
});
最后,這就是我發現的解決問題的方法。如果有人在上面的代碼中建議進行一些優化,那就太好了。謝謝。
- 1 回答
- 0 關注
- 109 瀏覽
添加回答
舉報