我在我的网站上实施了一个搜索栏,搜索会员卡以查找匹配的卡片。我也使用了Twitter的typeahead.js。当你输入时,结果会更新,所以我在输入框上设置了一个事件监听器 - $('#members-search .typeahead').on("input", changeFunction);
我还需要在建议上设置一个点击事件监听器,就像我做的那样 - {{ 1}}
似乎建议框是动态创建的,因此您无法在开头为所有(甚至任何!)设置事件监听器。我的第一个想法是在元素附加在包含div中时触发一个函数。但是,你需要一个事件监听器,我找不到。有没有办法实现这个?
JavaScript:
$('.tt-suggestion').on("click", changeFunction);
(重要)HTML:
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var children = document.getElementById("members-list").children;
var names = [];
var whoIsWho = [];
var selected = [];
var listOfAttributeNames = ["data-member-name", "data-member-username", "data-member-nickname"];
for(var i = 0; i < children.length; i++){
for(var j = 0; j < listOfAttributeNames.length; j++){
var a;
if(a = children[i].getAttribute(listOfAttributeNames[j])){
names.push(a);
whoIsWho.push(children[i]);
}
}
}
$('#members-search .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'names',
source: substringMatcher(names)
});
var previousValue = "";
function changeFunction(e){
var v;
if($("#members-search .typeahead").val() === ""){
previousValue = "";
}
else if(((v = $('#members-search .typeahead+pre').text())) !== previousValue){
previousValue = v;
}
else if(v !== $("#members-search .typeahead").val()){
previousValue = $("#members-search .typeahead").val();
}
selected = [];
v = $('#members-search .typeahead+pre').text();
for(var i = 0; i < names.length; i++){;
if(!(new RegExp(v, "i").test(names[i])) && !(selected.includes(whoIsWho[i]))){
whoIsWho[i].style.display = "none";
}
else{
selected.push(whoIsWho[i]);
whoIsWho[i].style.display = "block";
}
}
}
$('#members-search .typeahead').on("input", changeFunction);
$('.tt-suggestion').on("click", changeFunction);
我可以将Bloodhound脚本复制到我的代码中并修改元素的附加位置,但我宁愿不这样做,因为它使用了这种奇怪的IIFE格式,我不会花时间去理解。或者是否有其他解决方案,这个问题是X / Y问题的一部分?
答案 0 :(得分:0)
事实证明我做错了。我每次更改输入值时都会向当前建议添加一个事件监听器。
stroke(rgb);
strokeWeight(2);