在具有特定ID的元素(由變量myID提供)中搜索具有'some-class'類的元素。創建一個數組,而不是從jQuery使用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>
您可以添加此功能的完整編碼嗎? – msvairam
@msvairam我更新了我的問題。 – Evans
使用'.each' jQuery方法遍歷集合 –