What is the difference between $(this) and this

前端 未结 5 1760
北海茫月
北海茫月 2020-12-20 21:18

I have the following code

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

This works just fine and sure enough the returned

5条回答
  •  粉色の甜心
    2020-12-20 21:37

    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.

提交回复
热议问题