0

我在 javascript 中遇到了一些乱序执行,它与任何 ajax 调用等无关。大部分代码可能是缓慢的 DOM 操作,然后是方法调用。在每种情况下,函数调用都会在 DOM 操作完成之前被触发。

这是我的代码:

$(this).parents('dd').siblings('dd').each(function(){
  var filter_name = $(this).attr('data-filter-type');
  if ($(this).hasClass('selected')) {
    $(this).removeClass('selected', function(){
      if ($(this).hasClass('date')) {
        $('form[name="filter-form"] input[name="from"]').remove();
        $('form[name="filter-form"] input[name="to"]').remove();
      } else {
        $('form[name="filter-form"] input[name="' + filter_name + '"]').remove();
      }
      console.log('removed');
    });
  }
});

var filter_type = $(this).parents('dd').attr('data-filter-type');
var filter_input = 'form[name="filter-form"] input[name="' + filter_type + '"]';
if ($(filter_input).length > 0) {
  $(filter_input).val(filter_value);
} else {
  $('form[name="filter-form"]').append('<input type="hidden" name="' + filter_type + '" value="true">');
}

doStuff($(this));

在我的控制台中,我在看到调试之前看到了 doStuff 的结果。

有人知道如何让函数调用等待吗?

4

2 回答 2

1

There is an overload of .removeClass that takes a function, but it's not a callback function (that operation is completed synchronously). I'd recommend removing the function argument to removeClass and placing the code immediately after that call:

$(this).parents('dd').siblings('dd').each(function(){
    var filter_name = $(this).attr('data-filter-type');
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
        if ($(this).hasClass('date')) {
            $('form[name="filter-form"] input[name="from"]').remove();
            $('form[name="filter-form"] input[name="to"]').remove();
        } else {
            $('form[name="filter-form"] input[name="' + filter_name + '"]').remove();
        }
        console.log('removed');
    }
});

var filter_type = $(this).parents('dd').attr('data-filter-type');
var filter_input = 'form[name="filter-form"] input[name="' + filter_type + '"]';

if ($(filter_input).length > 0) {
    $(filter_input).val(filter_value);
} else {
    $('form[name="filter-form"]').append('<input type="hidden" name="' + filter_type + '" value="true">');
}

doStuff($(this));
于 2013-02-18T23:58:39.843 回答
0

我会将所有 DOM 操作包装到一个接受回调作为参数的函数中:

var manipulateDOM = function(callback){
...
if(typeof callback === "function")callback();
} 

并这样称呼它:

manipulateDOM(function(){
   doStuff(param);//I am not sure about the context so you need to figure out the value of param
})
于 2013-02-18T21:36:59.420 回答