代码之家  ›  专栏  ›  技术社区  ›  Chris

不要每次调用函数时都执行存储在数组中的jQuery

  •  6
  • Chris  · 技术社区  · 7 年前

    var remove = [
        jQuery("#mesh option:selected").removeAttr("selected"),
        jQuery("#pipetype option:selected").removeAttr("selected"),
        jQuery("#caboption option:selected").removeAttr("selected"),
        jQuery("#bedsize option:selected").removeAttr("selected"),
        jQuery("#model option:selected").removeAttr("selected"),
        jQuery("#year option:selected").removeAttr("selected"),
    ];
    
    
    for (var i = 0; i <= amount; i++) {
        remove[i];
    }
    

    我如何保证 deselect() 调用时,只执行少数数组元素,而不是全部执行?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Suresh Atta    7 年前

    你做错了。数组元素在您自己声明时执行。

    而不是你能做的一切

    var remove = [ "mesh","pipetype", "caboption","bedsize", "model","year"];
    for (var i = 0; i <= amount; i++) {
       jQuery("#"+remove[i]+" option:selected").removeAttr("selected"),
    }
    

    $("select option").prop("selected", false);
    
        2
  •  3
  •   Barmar    7 年前

    如果不希望立即执行它们,请将其设置为一个函数数组,并使用 ()

    var remove = [
        () => jQuery("#mesh option:selected").removeAttr("selected"),
        () => jQuery("#pipetype option:selected").removeAttr("selected"),
        () => jQuery("#caboption option:selected").removeAttr("selected"),
        () => jQuery("#bedsize option:selected").removeAttr("selected"),
        () => jQuery("#model option:selected").removeAttr("selected"),
        () => jQuery("#year option:selected").removeAttr("selected"),
    ];
    
    
    for (var i = 0; i <= amount; i++) {
        remove[i]();
    }