簡體   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