最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the difference between $(this) and this - Stack Overflow

programmeradmin3浏览0评论

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.

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 ....

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.

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 ....

Share Improve this question edited Sep 15, 2010 at 23:14 Stefan Kendall 67.8k69 gold badges257 silver badges409 bronze badges asked Sep 15, 2010 at 23:11 Dylan MuschDylan Musch 611 bronze badge 1
  • 1 possible duplicate of $(this) and this in jQuery – Matt Ball Commented Sep 15, 2010 at 23:54
Add a comment  | 

5 Answers 5

Reset to default 19

$(this) creates a jQuery object which wraps this. The native DOM object has an href attribute, but jQuery does not.

$(this).attr("href") would work.

this in your case is the actual dom element, so the anchor tag

$(this) is a jquery object that wraps that dom element with all the jquery goodness.

so .href is not an attribute of that jquery object, but it is of the dom object.

you could use $(this).attr('href') to achieve the same thing using the jQuery object.

This is because you're using a javascript DOMElement in the first example and a jQuery Object in the second example. The jQuery Object wraps around the DOMElement and provides you a lot of features.

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.

"this" in the code you've given above is a reference to the link's DOM element. $(this) creates a jQuery selection based upon the DOM element that contains only that link.

The jQuery selection will give you different features at the cost of a little performance. Your link element has a href property (i.e. one you can access through this.href) whereas the jQuery selection has all the normal jQuery properties & methods.

For getting the link target, this.href is definitely the way to go. 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);
});
发布评论

评论列表(0)

  1. 暂无评论