簡體   English   中英

如果使用jquery在div標簽中包含href,如何獲取href url

[英]How to get href url if href contains in div tag using jquery

如果href屬性包含在div標簽的錨標簽中,如何獲取href url

<div id="testing">
<a onclick="http://google.com">google</a>
<a href="http://facebook.com">facebook</a>
<a onclick="http://gmail.com">gmail</a>
</div>

您可以使用eq()從集合中通過索引獲取特定元素:

$('#testing a').eq(1);

或者

$('#testing a:eq(1)');

都將返回第二個a元素 - 在您的示例中指向facebook.com的鏈接。

獲得錨的另一種選擇

1) $("#testing a")[1].href

2) $("#testing a").eq(1).attr("href")

3) 通過屬性選擇器

 $("#testing a[href='http://facebook.com']").attr("href");

4) 這個沒有 jQuery

document.getElementById("testing").getElementsByTagName("a")[1].href

試試 jquery prop()eq()

$('a:eq(1)', $('#testing')).prop('href'); //<-- http://facebook.com

或者

$('a', $('#testing')).eq(1).prop('href'); //<-- http://facebook.com

或者

$('#testing').find('a').eq(1).prop('href'); //<-- http://facebook.com

或者

$('#testing').find('a:eq(1)').prop('href'); //<-- http://facebook.com

您將收集這些信息

// .eq( idx ) will give you the element at index idx (this begins from 0)
var $second_a_tag = $('#testing a').eq(1);

// .attr( attr_name ) will give you the value of attr_name attribute.
var href_attribute = $second_a_tag.attr('href');

如果您不關心保留$second_a_tag變量,您肯定可以組合這些行:

var href_attribute = $('#testing a').eq(1).attr('href');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM