2016-12-07 40 views
0

您好我已經在我的網頁一款標籤用在我有不同的ID多跨像下面有一個例子:通過ID獲取內部部分標籤的所有跨度使用jQuery

<section class="blog-summary-read col-md-6 col-md-offset-1"> 
 
    <span id="spnid2">2</span> 
 
    <span id="spnid3">3</span> 
 
    <span id="spnid4">4</span> 
 
    <span id="spnid5">5</span> 
 
    <span id="spnid6">6</span> 
 
</section>

我如何獲得使用jQuery的每個跨度ID?

+0

的可能的複製[jQuery - 選擇el從元素內部元素](http://stackoverflow.com/questions/5808606/jquery-selecting-elements-from-inside-a-element) –

回答

5

獲取所有span元素,然後迭代獲取id。

/** Method 1 : to get as an array **/ 
 

 
console.log(
 
    // get all span elements have id and within section 
 
    $('section span[id]') 
 
    // iterate to generate the array of id 
 
    .map(function() { 
 
    // return the id value 
 
    return this.id; 
 
    }) 
 
    // get array from jQuery object 
 
    .get() 
 
) 
 

 
/** Method 2 : for just iterating **/ 
 

 
$('section span[id]').each(function() { 
 
    console.log(this.id); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section class="blog-summary-read col-md-6 col-md-offset-1"> 
 
    <span id="spnid2">2</span> 
 
    <span id="spnid3">3</span> 
 
    <span id="spnid4">4</span> 
 
    <span id="spnid5">5</span> 
 
    <span id="spnid6">6</span> 
 
</section>

+1

Pranav,你的解決方案是完美的,我只是添加這個代碼與每個函數得到ID。 var spnid = $(this.id).selector;因爲如果我不使用選擇器在這裏獲得一些其他屬性也是不需要的。任何感謝您寶貴的解決方案。我正在投票答覆。 – Vikash

1

$('span').each(function(i, v) { 
 

 
    console.log($(this).attr('id')) 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section class="blog-summary-read col-md-6 col-md-offset-1"> 
 
    <span id="spnid2">2</span> 
 
    <span id="spnid3">3</span> 
 
    <span id="spnid4">4</span> 
 
    <span id="spnid5">5</span> 
 
    <span id="spnid6">6</span> 
 
</section>

迭代使用.each()然後得到使用attr()

0

現在你有3個版本,從...這選擇其ID每個跨度版本只選擇教區內的跨度離子帶班 「博客 - 總結 - 讀」

var spans = $('span', '.blog-summary-read'); 
 
spans.each(function(index, element){ 
 
    console.log($(element).attr('id')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section class="blog-summary-read col-md-6 col-md-offset-1"> 
 
    <span id="spnid2">2</span> 
 
    <span id="spnid3">3</span> 
 
    <span id="spnid4">4</span> 
 
    <span id="spnid5">5</span> 
 
    <span id="spnid6">6</span> 
 
</section>

0

使用每個函數u得到所有跨度的ID

$('.blog-summary-read span').each(function() { 
 
    console.log(this.id); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section class="blog-summary-read col-md-6 col-md-offset-1"> 
 
    <span id="spnid2">2</span> 
 
    <span id="spnid3">3</span> 
 
    <span id="spnid4">4</span> 
 
    <span id="spnid5">5</span> 
 
    <span id="spnid6">6</span> 
 
</section>

相關問題