jQuery each error :Uncaught TypeError: Cannot use 'in' operator to search for '18' in div[data-role=page]

前端 未结 3 1105
离开以前
离开以前 2021-01-18 21:46

My html is like

...
相关标签:
3条回答
  • 2021-01-18 22:11

    The key reason your code isn't working is because you're trying to iterate a string, which isn't what you really want to do.

    To iterate jQuery collections, try the other form of .each():

    $("div[data-role=page]").each(function() {
        //...
    });
    

    $.each() is (usually) for arrays or plain objects.

    0 讨论(0)
  • 2021-01-18 22:20

    You need to supply a jQuery collection, instead of just a selector to the $.each():

    $.each($("div[data-role=page]"), function (){
        console.log(this.id);
    });
    

    Or, even better:

    $("div[data-role=page]").each(function (){
        console.log(this.id);
    });
    

    Please note that I replaced $(this).attr('id') with this.id. It gets exactly the same property, but it's way more efficient.

    Fiddle Example

    0 讨论(0)
  • 2021-01-18 22:31

    An attribute value must be inside ' '

    Try something like this:

    $.each("div[data-role='page']", function (){
        console.log($(this).attr('id'));
    });
    
    0 讨论(0)
提交回复
热议问题