this.href和$(this).attr("href")之间的区别

3
可能重复:
this.href vs $(this).attr('href')

这是我的代码:

 $(function () {
        $("a.Delete").click(function () {
            console.log(this.href);
            console.log($(this).attr("href"));
            return false;
        });

and here is my link

<a class="Delete" href="/Contact/Delete/10402">Delete</a>

这是我的输出结果:

http://localhost:59485/Contact/Delete/10402
/Contact/Delete/10402

为什么attr方法不能直接获取属性呢?难道this.href获取的不就是属性吗?href属性有什么特殊之处,它能够直接给你绝对路径吗?

1
请看这里:https://dev59.com/fWw05IYBdhLWcg3w3lkl - dknaack
3个回答

6

HTML中的a元素具有类似于document.location对象的href属性。它将返回在[href]属性中指定的href的完全限定URL,包括协议、域名等。

jQuery的attr方法直接获取属性值。在幕后,它使用getAttribute(或等效)。

如果您想在原始JS中获取文本属性值,则可以使用:

anchor.getAttribute('href');

如果您想在jQuery中获取完全限定的URL,则可以使用以下代码:
$('a').prop('href'); //jQuery 1.6+

5
第一种方式,this.href 直接从浏览器使用的javascript实现中读取属性。这为您提供了一个绝对URL,因为浏览器正在解释href属性并将其与当前主机URL组合。
第二种方式,$(this).attr("href") 将元素包装在jQuery对象中,然后访问对象的 href 属性。返回的值没有进行任何处理,因此它只是简单地给出HTML中的确切字符串。

2

this.href 可以获得绝对URI。

$(this).attr("href") 可以获得href属性中的文本,可能是相对URI也可能是绝对URI。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接