我想使用類名訪問jQuery中的href屬性。我如何做到這一點是代碼。使用類名訪問href屬性
<a href="www.google.com" class="class-name">Hyper Link</a>
我只想使用類名來訪問它,因爲我有很多鏈接,並且希望使用類名來訪問href鏈接。
感謝
我想使用類名訪問jQuery中的href屬性。我如何做到這一點是代碼。使用類名訪問href屬性
<a href="www.google.com" class="class-name">Hyper Link</a>
我只想使用類名來訪問它,因爲我有很多鏈接,並且希望使用類名來訪問href鏈接。
感謝
取決於你想要什麼 - 但你的鏈接的href或許應該做成一個絕對的,而不是相對鏈接...
$('a.class-name').each(function(){
alert(this.href) // alerts http://currentdomain.com/www.google.com
alert($(this).attr('href')) // alerts www.google.com
})
$('a.class-name').each(function(){
this.href //do something with href
})
。假定(1)您使用jQuery 1.6和(2)你的鏈接,是具有類只有一個:
var linkHref = $('a.class-name').prop('href');
如果您正在使用jQuery 1.5或更高版本,則必須使用attr
而不是prop
。如果你的類有多個元素,你必須找到其他方法來確定你想要的元素。
爲了讓元素查找得更快,我建議您放棄標記前綴,因爲您提到您有很多鏈接。
$('.class-name').prop('href');
難道不應該是'$('的A.class - 名字')'用破折號而不是駝峯? – maerics 2011-06-15 17:40:08
@maerics,是的真的,對不起,我習慣於編碼某種方式,很難打破這種習慣 – Neal 2011-06-15 17:41:37
沒有後顧之憂,只是尋找雅= P – maerics 2011-06-15 17:43:28