【问题标题】:How to get href tag in <a> in <span> with jQuery?如何使用 jQuery 在 <span> 中的 <a> 中获取 href 标签?
【发布时间】:2016-01-22 16:46:54
【问题描述】:

就是这种情况:我有多个 &lt;span&gt; 标签,其类为 .productLink,其中一个链接 (&lt;a&gt;) 包含指向页面的链接。

示例

<span class="productLink">
    <a href="/Products/Category/item.html">A very nice product</a>
</span>
<span class="productLink">
    <a href="/Products/Category/otheritem.html">Also very nice product</a>
</span>

现在我想用 jQuery 检索这些链接。

我试过了:

$('.productLink').each(function(index){
    console.log($(this + ' a').attr('href'));
});

但它扔了:

未捕获的语法错误,无法识别的表达式:[object HTMLSpanElement]


See live fiddle

我需要改变什么?

【问题讨论】:

    标签: jquery html url hyperlink href


    【解决方案1】:

    您的语法不正确,this 语句中的$(this + ' a') 引用了 DOM 元素,因此报错。

    由于anchorproductlink 的子级,您可以使用任一方法遍历anchor,然后可以获取其href 属性。

    //Using context selector
    console.log($('a', this).attr('href'));
    
    //Using find method
    console.log($(this).find('a').attr('href'));
    
    //Using children method
    console.log($(this).children('a').attr('href'));
    

    【讨论】:

    • 我错过了什么吗?
    • 有时会出现不恰当的否决票而没有任何解释发生在我身上。
    【解决方案2】:

    您必须像这样在 jquery 选择器中选择锚标记:

    $('.productLink > a').each(function(index){
        console.log($(this ).attr('href'));
    });
    

    试试here

    【讨论】:

      【解决方案3】:
      console.log('start');
      $('.productLink').each(function(index){
          var a = $(this).find('a')
          console.log(a.attr('href'));
      });
      

      DEMO

      你需要在span中找到锚标签所以使用.find()获取锚标签后使用.attr()获取它的href

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-04
        • 2017-06-04
        • 2021-12-26
        • 2021-01-05
        • 2011-02-01
        • 2019-04-11
        • 2011-10-30
        • 2020-01-12
        相关资源
        最近更新 更多