javascript jQuery 每个错误:未捕获的类型错误:无法使用“in”运算符在 div[data-role=page] 中搜索“18”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23632737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:15:17  来源:igfitidea点击:

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

javascriptjqueryhtml

提问by Ammar Hayder Khan

My html is like

我的 html 就像

<div data-role="page" id="Dialog_1" data-url="Dialog_1">...</div>
<div data-role="page" id="Dialog_2" data-url="Dialog_2">...</div>
 .
 .
 .
<div data-role="page" id="Dialog_17" data-url="Dialog_17">...</div>
<div data-role="page" id="Dialog_18" data-url="Dialog_18">...</div>

i want to select all data-role="page" by the $.each

我想通过 $.each 选择所有 data-role="page"

My jQuery

我的jQuery

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

it is giving the error:

它给出了错误:

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

http://jsfiddle.net/8xUy3/

http://jsfiddle.net/8xUy3/

回答by Cerbrus

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

您需要提供一个 jQuery 集合,而不仅仅是一个选择器$.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.

请注意,我替换$(this).attr('id')this.id. 它获得完全相同的属性,但效率更高。

Fiddle Example

小提琴示例

回答by Jason P

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():

要迭代 jQuery 集合,请尝试另一种形式.each()

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

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

$.each()是(通常)用于数组或普通对象。

回答by Tiago Guedes

An attribute value must be inside ' '

属性值必须在“ ”内

Try something like this:

尝试这样的事情:

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