2016-12-07 35 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>

相关问题