jQuery “TypeError: invalid 'in' operand a”

荒凉一梦 提交于 2020-01-14 10:30:05

问题


I have the following json array returning from an ajax call:

{"err":"err_type","fields":["field1","field2"]}

when tryin to print it out with this function:

$.each(data.fields, function (i, field) {
    console.log(field);
    $.each(field, function (j, f) {
        $('[name="'+f+'"]').addClass('form_err');
        console.log(f);
    });
});

i get this:

data1

TypeError: invalid 'in' operand a
...turn function(b){return db(a,b).length>0}}),contains:fb(function(a){return funct...

and so i can't figure out how to use this array! Anyone have any idea?


回答1:


You are iterating a string, you don't need two .each() functions

$.each(data.fields, function (i, field) {
    $('[name="'+field+'"]').addClass('form_err');
    console.log(field);
});



回答2:


Remember to add dataType: 'json'; so that it can be looped as an array and not a string.




回答3:


You don't need another loopin $.each():

$.each(data.fields, function (i, field) {
   console.log(field);
   $('[name="'+field+'"]').addClass('form_err');
});

data.fields is an array which contains strings only, so you don't need to loopin again. You just need to loopin only when if it would be another array object with {key:value} pairs.




回答4:


In your main loop, the "field" var is not an array, so you can't use "each" on it.



来源:https://stackoverflow.com/questions/24429957/jquery-typeerror-invalid-in-operand-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!