繁体   English   中英

jQuery数据HTML属性不返回值

[英]JQuery data html attribute not returning value

这是我的html:

<ul class="inboxList">
    <li data-selecttype='global|mailbox|inbox'>Inbox</li>
</ul>

这是我的jquery代码:

$(".inboxList").children().each(function(child){
    console.log($(child).data("selecttype"));
});

我也尝试取出孩子的$():

$(".inboxList").children().each(function(child){
    console.log(child.data("selecttype"));
});

但这没有用。

我的返回值为null且未定义。 我期望返回值是global|mailbox|inbox我做错了什么?

感谢您的协助!

您在每个的回调中使用了错误的参数。 您应该为元素使用第二个arg或抛弃args并仅使用this 它应该是:

$(".inboxList").children().each(function(i, child){ // each has 2 args first one is index and second one is the element.
    console.log($(child).data("selecttype")); //Or this

    console.log($(this).data('selecttype'));
});

http://jsfiddle.net/JUyHg/

.each(function(index(Element,Element))

尝试这个,

$(".inboxList").children().each(function(){
    console.log($(this).data("selecttype"));
});

根据jQuery网站上的定义,.each()接受2个参数indexElement ,其中,

index-是.each()返回的jQuery对象中当前匹配元素的索引。

元素-在您的情况下是当前元素

 <li data-selecttype=​"global|mailbox|inbox">​Inbox​</li>​ 

进一步了解.each()

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM