【问题标题】:Get certain attribute of all anchors of certain class [closed]获取某个类的所有锚点的某个属性[关闭]
【发布时间】:2013-07-06 16:59:35
【问题描述】:

我想在 jQuery 中获取具有特定类的所有 <a> 标记的 name 属性。我该怎么做。

说这是我的 HTML:

<div>
    <a href="#" name="first" class="myClass">Something</a>
</div>
<a href="#" name="second">Something else</a>
<a href="#" name="third" class="myClass">Something else again</a>

所以我需要获得“第一”和“第三”,因为它们有 myClass 类。锚‘第三’没有这个类,所以我不需要它。

【问题讨论】:

  • @sambit.albus,我改变了你的问题,所以更清楚你在问什么。请考虑您的问题将如何看待 SO 的其他访问者。包含代码并说明您已经尝试过的内容总是很好。另外,请确保您的标题与问题相对应(即您没有提及您想要访问属性的事实)。

标签: jquery


【解决方案1】:

使用类选择器.prop() 来获取属性。attr() 如果您使用的是旧版本的jquery(之前的jquery 1.6) 试试这个...

$('.className').prop('name'); //calssName is the name of your class

对于多个元素

$('.className').each(function(){
   console.log($(this).prop('name')) 
});

使用map()

 var nameArray= $('.class').map(function(){
   return this.name;
 }).get();

 console.log(nameArray);  //nameArray is an array with all the names

fiddle usign map

例子..

<a name="test" class="class">test</a>

alert($('.class').prop('name'));

【讨论】:

  • 感谢@bipen 我如何访问多个值。它会返回一个数组吗?
  • 已更新,请检查... :)
  • 谢谢哥们,它就像一个魅力
  • 欢迎......朋友......很高兴它有帮助......快乐编码......
【解决方案2】:

试试这个Working Demo

$('div.divClass').children('a.anchorClass').each(function( index ) {
    alert($(this).prop('name'));
});

【讨论】:

    【解决方案3】:
    var array = new Array();    
    
    $('a.className').each(function(){
       array.push($(this).prop('name'));
    })
    

    迭代数组以获取'a'标签的所有属性名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多