开发者

jQuery selector with context passing

I am working on a jQuery tutorial and there's something that I don't quite understand why. Below is the section that I cut out of the tutorial. The sentence in bold is the part that I don't understand and would like some expert to explain开发者_StackOverflow中文版 it to me. Much appreciated!

"A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function. Example:

 function addClickHandlers() {
   $("a.remote", this).click(function() {
     $("#target").load(this.href, addClickHandlers);
   });
 }

$(document).ready(addClickHandlers); Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading.

Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually."


function addClickHandlers() {
    // this is window
    $("a.remote", this).click(function() {
        // this is a <a class="remote">
        $("#target").load(this.href, addClickHandlers);
    });
}

In general the this context in a function is window unless it's called with the new keyword or if it's called as obj.method() (in which case it's obj).

Because calling a function addClickHandlers() actually calls window.addClickHandlers() which means that the this value is scope to window.

Where as jQuery itself will scope this to be the element your using inside call back functions.

In .click(function() { ... }) this will refer to the object that was clicked on.


Why can't you just perform a live() handler bind, like so:

$('#target .elements').live('click', function() {
  ...
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜