简体   繁体   English

按类别获取ID中的元素

[英]Get element in ID by class

I have some HTML: 我有一些HTML:

<div id="bin">
    <span class="item1 selectMe">1</span>
    <span class="item2 selectMe">2</span>
    <span class="item3 dontSelectMe">3</span>
</div>

I would like to return an array with the values in the span elements which contain the selectMe class. 我想返回一个数组,其中包含包含selectMe类的span元素中的值。 This is what I've written: 这是我写的:

var values = [];
$('#bin span.selectMe').each(function() {
    values.push($(this).text());
});

However, when I print values to the console, it is always empty. 但是,当我将values打印到控制台时,它始终为空。 Any thoughts on why I am not iterating through the bin ? 关于为什么我不遍历bin什么想法?

The following should work, however what you paste above should seem to also: 以下应该起作用,但是您上面粘贴的内容似乎也应该起作用:

var values = $('#bin span.selectMe').map(function(){
  return $(this).html();
});

What you have should work, but here is a more elegant solution: 您所拥有的应该可以工作,但是这里有一个更优雅的解决方案:

var values = $('#bin span.selectMe').map(function() {
    return $(this).text();
}).get();
var values = [];
$('#bin').find('span.selectMe').each(function() {
     values.push($(this).text());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM