jQuery get 每个元素的属性

jQuery get attribute of every element

本文关键字:属性 元素 get jQuery      更新时间:2023-09-26

所以一开始我想指出我检查了其他线程,但它们没有帮助我。

所以我得到了这样的台词:

$('div.fsl.fwb.fcb');

它给了我所有这些div 元素,这很酷,但我只想要 hrefs 值,所以我这样做

$('div.fsl.fwb.fcb').find('a').attr('href');

根据jQuery文档,它只给了我第一个元素值,这就是它应该的样子,它说我应该使用.each()或.map()函数,所以我使用.each()

$('div.fsl.fwb.fcb').each(function(){$(this).find('a').attr('href')});

但是它没有给我值,而是给了我整个div,就像我会把这样的代码放在一起。

$('div.fsl.fwb.fcb'); 

我已经在这个论坛上检查了一个关于这个问题的线程,但答案是在每个函数内创建一个数组,但我更愿意在函数返回时获取这个数组,而不是全局变量。可能吗?

关键是确定包含该属性的元素集并迭代:

$('div.fsl.fwb.fcb').find('a').each(function(){
    $(this).attr('href');
});

编辑2:想要它在数组中:

var myNewArray = [];
$('div.fsl.fwb.fcb').find('a').each(function(){
    myNewArray.push($(this).attr('href'));
});

编辑:这实际上只是同一想法的另一个例子:

var arrayofhref = $('div.fsl.fwb.fcb').find('a').map(function(){
     return $(this).attr('href');
 }).get();

并将其扩展到:

var commanlistofhref = $('div.fsl.fwb.fcb').find('a').map(function(){
     return $(this).attr('href');
 }).get().join();

EDIT3:创意使用示例:将某些元素作为文本附加到某个元素并将其放入对象中并显示;

var myobj = {
  hrefs: []
};
$('div.fsl.fwb.fcb').find('a').each(function() {
  myobj.hrefs.push({
    href: $(this).attr('href')
  });
  $('#results').append($(this).attr('href') + '<br />');
});
$('#results').append(JSON.stringify(myobj));

玩的创意用途:https://jsfiddle.net/4mbh9ra4/

$('div.fsl.fwb.fcb a').each返回匹配的元素,而不是回调函数中的返回值,这就是您获取所有div 的原因:

var hrefs = [];
var divs = $('div.fsl.fwb.fcb a').each(function(){
  hrefs.push($(this).attr('href'));
});
console.log(divs); //all divs
console.log(hrefs); //all hrefs
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="fsl fwb fcb">
   <a href="http://foo.com">Foo</a>
</div>
<div class="fsl fwb fcb">
   <a href="http://bar.com">Bar</a>
</div>

您可以使用

map()函数执行以下操作。

var arr= $('div.fsl.fwb.fcb a').map(function(){
     return this.href;
}).get();
console.log(arr);
你可以

做类似的事情

$('div.fsl.fwb.fcb > a').each(function(index, item){$(item).attr('href')});