2017-08-25 67 views
6

我目前在一个存储在一个函数中的数组中存储了几个jQuery片段。一旦我从我的代码库调用函数,就会执行每个jQuery代码片段。因此,阻止我在阵列中工作。每次调用函数时都不要执行存储在数组中的jQuery

下面的代码是一个例子:

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()被调用时,只有少数的数组元素得到执行,而不是所有的人?

谢谢!

回答

5

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

而是一切你可以做

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); 
3

如果你不”不希望它们立即执行,使它成为一组函数,然后在()的循环中调用它们。

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](); 
} 
相关问题