this.href vs $(this).attr('href') [英] this.href vs $(this).attr('href')

查看:558
本文介绍了this.href vs $(this).attr('href')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读本文后, net.tutsplus。 com / tutorials / javascript-ajax / 14-helpful-jquery-tricks-notes-and-best-practices / 我得出结论,使用 this.href 会更有效率。



然而,当我尝试在我的一个项目中使用它时,我看到 this.href 不仅返回href而且还附加了一个网站的网址。例如< a href =tab-04>< / a> this.href 将返回 http://example.com/abc/tab-04 $(this).attr('href')将只返回tab-04。



您可以在此处查看示例 http://jsfiddle.net/UC2xA/ 1 /



$(this).attr('href')然而,正是我所需要的,仅此而已。



我的问题是,如何重写(或做必要的) this.href ,以便它只返回 tab-04



编辑



道格你是对的

 this.getAttribute('href')

解决方案

普通Javascript中的 href 属性将附加语义。它返回链接将导致的目标URL。它的编写方式无关紧要(绝对或相对URL)。



当你使用 $(this).attr(href时)您正在直接检索 href 属性的值,就像任何其他属性一样,因此它将返回HTML中呈现的确切值。 / p>

对于你的情况,最好使用 $(this).attr(href)



如果您不想使用jQuery,还有另一种解决方案,只使用普通的JavaScript:

  this.getAttribute('href')


After reading this article net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best-practices/ I came to conclusion that using this.href is more efficient.

However, when I tried to use it on one of my projects, I saw that this.href returns not only href but also appends a url of a website. For example <a href="tab-04"></a>this.href will return http://example.com/abc/tab-04 and $(this).attr('href') will return only tab-04.

You can see an example here http://jsfiddle.net/UC2xA/1/.

$(this).attr('href') however returns exactly what I need and nothing more.

My question is this, how can I rewrite (or do what is necessary) this.href so that it would only return tab-04?

EDIT

Doug you are right on the money with

this.getAttribute('href')

解决方案

The href property in plain Javascript will have the semantic attached to it. It returns the destination URL which the link will lead to. It doesn't matter how it was written (absolute or relative URLs).

When you use the $(this).attr("href") you are retrieving directly the value of href attribute just like any other attribute, so it will return the exact value rendered in the HTML.

For your case then, it's better to use $(this).attr("href")

If you don't want to use jQuery, there's yet another solution, using just plain JavaScript:

this.getAttribute('href')

这篇关于this.href vs $(this).attr('href')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆