为什么这些功能会重复出现?

时间:2013-06-25 15:12:20

标签: javascript function recursion

如果我执行以下功能的步骤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 五 6 4 五 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;
}

});

3 个答案:

答案 0 :(得分:0)

步骤4实际上并不执行日志记录和隐藏和拼接,而是将这些事件挂钩到click元素的.search-tag事件。

从这个角度来看,再次查看你的代码,找出你应该运行这些代码的顺序。

答案 1 :(得分:0)

您可以创建一个名为once的全局变量,并将其设置为1.然后,在步骤3中围绕if创建一个tagRemover(selected);语句,检查once == 1是否为once = 0。然后,一旦进入if语句集{{1}},这样它就不会再次执行。

答案 2 :(得分:0)

clickhandler(2)调用returnselected(3)调用tagRemover(4)调用spliceAndSearch(5)调用queryMaker(6)

tagRemover只会在获得搜索标签匹配时记录4,因此您的控制台日志略有欺骗性

您已将step1(以及步骤4)绑定到“更改”功能,因此它们几乎不可避免地会运行相同的次数。

相关问题