each() 函数跳过 JQuery 并且对数组不做任何事情

each() function skips in JQuery and does nothing on arrays

我编写了这段代码来迭代 Reshte 数组的每个元素,但它跳过了所有元素并且它的内容永远不会运行

Reshte = $('.seeker_register select[name="Reshte[]"]').toArray();
Gerayesh = $('.seeker_register select[name="Gerayesh[]"]').toArray();
Moadel = $('.seeker_register select[name="Moadel[]"]').toArray();

// Reshte.each(function(index, el) {
 Reshte.each(function(index, el) {
    if ($(Reshte[index].val() )){
        review_page += 'Diplom: '+
        $(Reshte[index]).val()+ '   '+
        $(Gerayesh[index]).val()+ '  Moadel:'+
        $(Moadel[index]).val();
    };
});

Reshte 数组不为空。就是这样:

Reshte =
Array [ <select#Reshte.form-control>, <select#Reshte.form-control>, <select#Reshte.form-control>, <select#Reshte.form-control>, <select#Reshte.form-control> ]

在Javascript中你可以使用for

for (var i = 0; i < Reshte; i++) {
    //alert(Reshte[i]);
    //Do something
}

你可以使用Jquery方法$.each()

$.each(Reshte, function(index, el){
  // your code
});

在您的代码中,如果您使用:Reshte.each

,则会出现错误

Uncaught TypeError: undefined is not a function

你不需要它们作为数组,它们已经这样存储了,jQuery 给你一个很好的 each() 方法来遍历它们和一个 eq() 方法来访问它们按数组索引。 each() 不存在于数组中它只起作用,因为它继承了 jQuery 自己的每个方法。

您的 if 条件 $(Reshte[index].val() ) 中也有一个错误。 Reshte[index] 不会将 val() 作为原生 DOMElement。即使它这样做了,当元素是您想要传递的元素时,它也会获取该值并将其传递给 $() 并在其上调用 val()

Reshte = $('.seeker_register select[name="Reshte[]"]');
Gerayesh = $('.seeker_register select[name="Gerayesh[]"]');
Moadel = $('.seeker_register select[name="Moadel[]"]');

Reshte.each(function(index) {
    if ($(this).val()){ // bug fix here
        review_page += 'Diplom: '+
        $(this).val() + '   '+
        Gerayesh.eq(index).val() + '  Moadel:'+
        Moadel.eq(index).val();
    };
});

您不需要调用 toArray(),因为 .each() 是一个 jQuery 方法,应该在 jQuery 对象上调用。 JS 数组不是 jQuery 对象。

所以简单地删除它应该没问题。