2016-03-02 27 views
1

在具有特定ID的元素(由變量myID提供)中搜索具有'some-class'類的元素。創建一個數組,而不是從jQ​​uery使用dom獲取的值的變量?

對於其中的每一個我需要獲取數據屬性的值稱爲'data-att'。 然後我想創建一個這樣的數組,但將字符串custom-class--添加到每個的開頭。

我的代碼如下,除了它只產生1值。我怎樣才能創建一個數組而不是一個變量?

// a in the ID of the container to search in for elements with a class of 'some-class' 
var myID = '#' + myID; 

// Create a varialbe which starts 'custom-class--' and then has the data-att attribute 
// of elements for elemts with a class of 'some-class' 
var class = 'custom-class--' + $(myID).find('.some-class').attr('data-att'); 

更新 - 這裏是一個工作codepen:http://codepen.io/anon/pen/reVeja?editors=1111

<a href="#" class="some-class" data-att="data-1">Link</a> 

<div id="my-id"> 
    <a href="#" class="some-class" data-att="data-2">Link</a> 
    <a href="#" class="some-class" data-att="data-3">Link</a> 
</div> 

<script type="text/javascript"> 

$(function() { 

    // a in the ID of the container to search in for elemnts with a class of 'some-class' 
    var myID = '#' + 'my-id'; 

    // Create a variable which starts 'custom-class--' and then has the data-att attribute 
    // of elements for elements with a class of 'some-class' 
    var myClass = 'custom-class--' + $(myID).find('.some-class').attr('data-att'); 

    console.log(myClass); 

}); 
</script> 
+0

您可以添加此功能的完整編碼嗎? – msvairam

+0

@msvairam我更新了我的問題。 – Evans

+0

使用'.each' jQuery方法遍歷集合 –

回答

4

你可以嘗試這樣的事情:

var myID = '#' + myID; 
var elemClass=[]; 

$(myID).find('.some-class').each(function(){ 
    if($(this).attr('data-att').length){ 

     elemClass.push('custom-class--'+ $(this).attr('data-att')) ; 
    } 

}); 

,請注意您不能使用reserved wordsclass你碼。

1

您可以使用map()來遍歷元素並自動創建一個新的數組,其中填充了您從地圖回調中返回的值。在回調,我使用data()得到data-att的價值:

var parentId = '#PARENTID', 
    clNames = $.map($(parentId).find('.some-class'), function(i,el){ 
     return 'custom-class--'+ $(el).data('att'); 
    }); 

但要知道,這一個總是返回一個值,即使你沒有在元素上的data-att屬性。如果您的案件沒有data-att,您將以custom-class--undefined結束。這不是一個真正的問題,甚至可以將它用作默認樣式。

相關問題