如果我两次执行以下函数的第 1 步(每一步依次触发第 2、3、6 步),我希望能够执行第 4 步一次,而不会重复执行与第 1 步相同的次数(第 4 步触发第 5 步和第 6 步)。
为什么第 4 步(及其后续功能)重复执行第 1 步(及其后续功能)的次数相同?
$(function(){
var selected = [], clickHandler;
var el = document.getElementById("user_search_tags");
el.addEventListener("click", returnSelected, false);
// step 1
$('#people_search_mobile').change(function() {
console.log(1);
$('li a', $('#suggestions')).bind('click.autocomplete', clickHandler);
});
// step 2
function clickHandler() {
console.log(2);
selected.push($(this).text());
returnSelected(selected);
queryMaker(selected);
}
// step 3
function returnSelected(selected) {
console.log(3);
tagRemover(selected);
}
// step 4
function tagRemover(selected) {
$('.search-tag').click(function(){
console.log(4);
$(this).hide();
spliceAndSearch($(this).text(), selected);
})
}
// step 5
function spliceAndSearch(removed, selected) {
console.log(5);
selected.splice(selected.indexOf(removed), 1);
queryMaker(selected);
}
// step 6
function queryMaker(selected) {
$('#uquery').val(selected);
$.get(this.action, $('#people_search_mobile').serialize(), null, 'script');
$('#uquery').val('').focus();
console.log(6);
return false;
}
});
这是我的控制台日志的摘要(步骤为数字):
1 2 3 6 1 2 3 6 4 5 6 4 5 6 3
谢谢你。
解决方案
$(函数(){
var selected = [];
var clickHandler;
$('#people_search_mobile').change(function() {
$('li a', $('#suggestions')).bind('click.autocomplete', clickHandler);
});
$('body').on('click', '.search-tag', tagRemover);
function tagRemover() {
$(this).hide();
console.log(selected);
selected.splice(selected.indexOf($(this).text()), 1);
queryMaker(selected);
}
function clickHandler() {
selected.push($(this).text());
returnSelected(selected);
queryMaker(selected);
}
function returnSelected(selected) {
var saySelected = function() { alert(selected); }
return saySelected;
}
function queryMaker(selected) {
$('#uquery').val(selected);
$.get(this.action, $('#people_search_mobile').serialize(), null, 'script');
$('#uquery').val('').focus();
return false;
}
});