使用classname访问href属性

时间:2011-06-15 17:36:28

标签: javascript jquery css

我想使用类名使用jquery访问href属性。我怎么能这样做是代码。

<a href="www.google.com" class="class-name">Hyper Link</a>

我只想用类名访问它,因为我有很多链接,并希望使用类名来访问href链接。

谢谢

4 个答案:

答案 0 :(得分:4)

$('a.class-name').each(function(){
     this.href //do something with href
})

答案 1 :(得分:2)

假设(1)您正在使用jQuery 1.6和(2)您的链接是唯一拥有该类的链接:

var linkHref = $('a.class-name').prop('href');

如果您使用的是jQuery 1.5或更早版本,则必须使用attr而不是prop。如果你有一个以上的元素,你必须找到一些其他的方法来识别你想要的元素。

答案 2 :(得分:1)

取决于你想要的东西 - 但你的链接的href可能应该是绝对的而不是相对的链接......

    $('a.class-name').each(function(){
        alert( this.href ) // alerts http://currentdomain.com/www.google.com
        alert( $(this).attr('href') ) // alerts www.google.com
    })

答案 3 :(得分:0)

为了让元素更快地查找,我建议删除标记前缀,因为你提到你有很多链接。

$('.class-name').prop('href');
相关问题