【发布时间】:2019-01-28 15:43:02
【问题描述】:
我有以下使用 typeahead.js 的函数,它绑定在输入字段上。
问题是当用户从下拉列表中选择值时,我试图传递自定义函数。
所以它第一次只发送正确的值(一次)。对于下一个选择,它会发送两次相同的值。从下拉列表中选择新时,它会随机发送 4 次。 从下拉列表中选择时,它应该只传递一次变量。
$(document).on('mouseenter', '.js-ma-product-autocomplete', function (e) {
var current_handler = $(this).attr('id');
$('#' + current_handler).typeahead("destroy");
var current_selected_id = $(this).siblings('.js-ma-linked-product-id').attr('id');
var current_selected_type = $(this).siblings('.js-ma-linked-product-type').val();
var current_selected_container = $(this).siblings('.js-ma-linked-product-container').val();
var current_selected_btn = $(this).siblings('.js-ma-linked-product-add-btn').val();
var initialize_master_agent_products_typeahead;
initialize_master_agent_products_typeahead = function () {
var master_agent_products_typeahead;
master_agent_products_typeahead = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("name"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/productions/mas_products_autocomplete?query=%QUERY",
replace: function (url, uriEncodedQuery) {
return url.replace("%QUERY", uriEncodedQuery) + '&product_type=' + encodeURIComponent(current_selected_type)
},
filter: function (list) {
if (list.length == 0) {
$('#' + current_selected_id).val('');
}
return list;
}
}
});
master_agent_products_typeahead.initialize();
$('#' + current_handler).typeahead(null, {
displayKey: "name",
source: master_agent_products_typeahead.ttAdapter(),
templates: {empty: "<div> No matching products found </div>"}
});
$('#' + current_handler).one('typeahead:selected', function (event, datum, name) {
var count = 1;
$('#' + current_selected_id).val(datum.id);
show_options(current_selected_type);
create_fields(current_selected_id, current_selected_type, current_selected_container, current_selected_btn, datum.id, datum.name, count++); // from this part its calling more than once.
});
};
initialize_master_agent_products_typeahead();
});
function create_fields(c_p_id, c_p_type, c_p_container, c_p_btn, l_p_id, l_p_name, count){
// var minNumber = 300;
// var maxNumber = 400;
// var randomNumber = randomNumberFromRange(minNumber, maxNumber);
// debugger;
console.log(c_p_id);
console.log(c_p_type);
console.log(c_p_container);
console.log(c_p_btn);
console.log(l_p_id);
console.log(l_p_name);
console.log(count);
console.log('*****************');
//here it sends values multiple times
}
【问题讨论】:
标签: javascript jquery ruby-on-rails typeahead.js twitter-typeahead