简体   繁体   English

$(this)和this之间有什么区别?

[英]What is the difference between $(this) and this

I have the following code 我有以下代码

$('a').click(function() {
var url= this.href;
alert(url);
});

This works just fine and sure enough the returned result is the url of a tag. 这很好用,确定返回的结果是标记的url。

However if I change the above code to 但是,如果我将上面的代码更改为

$('a').click(function() {
var url= $(this).href;
alert(url);
});

The result is undefined. 结果未定义。

Anyone please help to clear this out for me? 有人请帮忙清除这个吗? I am banging my head for this .... 我为此敲打我的脑袋....

$(this) creates a jQuery object which wraps this . $(this)创建一个包装this的jQuery对象。 The native DOM object has an href attribute, but jQuery does not. 本机DOM对象具有href属性,但jQuery没有。

$(this).attr("href") would work. $(this).attr("href")可以工作。

this in your case is the actual dom element, so the anchor tag this在你的情况是实际的DOM元素,所以锚标签

$(this) is a jquery object that wraps that dom element with all the jquery goodness. $(this)是一个jquery对象,它包含了所有jquery良好的dom元素。

so .href is not an attribute of that jquery object, but it is of the dom object. 所以.href不是该jquery对象的属性,但它是dom对象。

you could use $(this).attr('href') to achieve the same thing using the jQuery object. 您可以使用$(this).attr('href')来使用jQuery对象实现相同的功能。

This is because you're using a javascript DOMElement in the first example and a jQuery Object in the second example. 这是因为您在第一个示例中使用了javascript DOMElement,在第二个示例中使用了jQuery Object。 The jQuery Object wraps around the DOMElement and provides you a lot of features. jQuery Object包含DOMElement并为您提供了许多功能。

You can access the url as follow: 您可以访问以下网址:

$('a').click(function() { var url= $(this).attr('href'); alert(url); });

The difference is between a DOM element and a jQuery selection. 区别在于DOM元素和jQuery选择。

"this" in the code you've given above is a reference to the link's DOM element. 您在上面给出的代码中的“this”是对链接的DOM元素的引用。 $(this) creates a jQuery selection based upon the DOM element that contains only that link. $(this)基于仅包含该链接的DOM元素创建jQuery选择。

The jQuery selection will give you different features at the cost of a little performance. jQuery选择将以一点点性能为代价为您提供不同的功能。 Your link element has a href property (ie one you can access through this.href) whereas the jQuery selection has all the normal jQuery properties & methods. 你的link元素有一个href属性(即你可以通过this.href访问),而jQuery选择有所有正常的jQuery属性和方法。

For getting the link target, this.href is definitely the way to go. 为了获得链接目标,this.href绝对是要走的路。 It is simpler, faster and less verbose. 它更简单,更快速,更简洁。

Lots of good answers, just wanted to add that you could also do this: 很多好的答案,只是想补充说你也可以这样做:

$('a').click(function(e) {
    alert($(this)[0].href);
});

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

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