简体   繁体   English

使用类名访问href属性

[英]accessing href attribute with classname

I want to access the href attribute with jquery using the class name. 我想使用类名通过jquery访问href属性。 How can I do that below is the code. 下面是我该怎么做的代码。

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

I only want to access it with the class-name since I have many links and want to use the classname to access the href link. 我只想使用类名来访问它,因为我有很多链接,并且想使用类名来访问href链接。

Thanks 谢谢

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

Presuming (1) that you are using jQuery 1.6 and (2) that your link is the only one that has that class: 假设(1)您正在使用jQuery 1.6,并且(2)您的链接是唯一具有该类的链接:

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

If you are using jQuery 1.5 or older, you'll have to use attr rather than prop . 如果您使用的是jQuery 1.5或更早版本,则必须使用attr而不是prop If you have more than one element with the class, you'll have to find some other way of identifying which element you want. 如果类中有多个元素,则必须找到其他方法来标识所需的元素。

Depends what you want - but the href of your link should probably be made into an absolute rather than relative link... 取决于您想要的内容-但您的链接的href可能应该设为绝对而非相对链接...

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

为了使元素查找更快,我建议您删除标签前缀,因为您提到您有很多链接。

$('.class-name').prop('href');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM