2017-02-10 68 views
-1

我有脚本在选择框中显示下拉菜单。目前我正在使用的脚本是将jquery的每个函数转换为纯javascript

jQuery.each(dslr, function(index, dslrgp) { 
    var aslrp= dslrgp.aslrp; 
    jQuery.each(aslrp, function(index2, pslrp) { 
     var found = 0; 
     jQuery.each(dropdown, function(index3, dditem) { 
      if (dditem.countryname == pslrp.countryname) 
      { 
       foundit = 1; 
      } 
     }); 
     if (foundit == 0) 
      dropdown.push(pslrp); 

    }); 
}); 

我该如何将其转换为纯javascript。因为如果我使用这个

dslr.forEach(function(index, dslrgp) { 
    var aslrp= dslrgp.aslrp; 
    aslrp.forEach(function(index2, pslrp) { 
     var found = 0; 
     dropdown.forEach(function(index3, dditem) { 
      if (dditem.countryname == pslrp.countryname) 
      { 
       foundit = 1; 
      } 
     }); 
     if (foundit == 0) 
      dropdown.push(pslrp); 

    }); 
}); 

它不起作用。

+1

“它不工作” - 定义 “不工作”。给出一个明确的问题陈述。你得到的行为与你期望的行为有什么不同? – Quentin

+1

“将jquery的每个函数转换为纯javascript” - jQuery **是纯JavaScript代码。有完全有效的理由想要移除对jQuery的依赖,但不要将jQuery误认为是JavaScript以外的任何东西。 – Quentin

+0

我编辑了我的问题。 –

回答

1

注意参数在本机forEach中的差异 - 首先是item的值,second是index。因此,而不是:

aslrp.forEach(function(index2, pslrp) { 
... 
dropdown.forEach(function(index3, dditem) { 

使用本:

aslrp.forEach(function(pslrp, index2) { 
... 
dropdown.forEach(function(dditem,index3) { 
1

您正在使用.forEach()方法是错误的。 forEach docs

您不需要将数组作为第一个参数传递。只需传递回调即可。

dslr.forEach(function(dslrgp) { 
    // do something.. 
} 

或键/值迭代

dslr.forEach(function(value, index) { 
    // do something.. 
}