开发者

bind this keyword for non-anonymous functions

Let say I have the following code

$("p").bind("click", function(){
  alert( $(this).text() );
});

When the user clicks a <p>, an alert show up. What's good here, is that I make use of the "this" keyword.

Now I want to get rid of the anonymous function (using it multipl开发者_如何学Ce time per script);

$("p").bind("click", myfunction());
myfunction(){
  alert( $(this).text() );
}

this now refer to Window. How can i do to fix that?

Update:

A suggested solution by answerers that actually works

$(function(){
    $("p").bind("click", function() { myfunction($(this));});

    function myfunction(elem)
    {
      alert( elem.text() );
    }
});

This is good, but you'll finish creating a new function every time that line of code is called, no?


You want to pass the original "this" (the context) to the function.

In Javascript, that's done by using call. Eg, see here

So I modify Jonathon's answer:

$("p").bind("click", function(){ myFunction.call(this); });

function myfunction(){
  alert($(this).text());
}

Added:

I looked up jquery bind and Jonathon is right, the context is automatically set to be the original element that you're adding the event listener to.

I think the real issue is that you're not passing in the function ref correctly.

Try

$("p").bind("click", myfunction);
var myfunction = function(){
  alert( $(this).text() );
}


Something like

$(function(){
    $("p").bind("click", function() { myfunction($(this));});

    function myfunction(elem)
    {
      alert( elem.text() );
    }
});

Here also you are not removing the anonymous function. But inside that you can call another function.


I was just thinking, why would you want to do it that way?

$("p").bind("click", function(){
  alert( $(this).text() );
});

when you can add up more selector like this:

$("p,div,li,:button").bind("click", function(){
  alert( $(this).text() );
});


You can do this to get the real element that invoked the handler..

function myfunc(e)
{
  var _this = e.currentTarget;
  alert( $(_this).text());
}

according to jQuery documentation

event.currentTarget

Description: The current DOM element within the event bubbling phase.

version added: 1.3

This property will always be equal to the this of the function.


The problem there was that your event handler was calling the function, myfunction(), versus passing a reference to it, myfunction. That's what changed the scope it was running in. If you pass the function a parameter, myfunction, "this" should work as expected.

More generally, if all you really care about is knowing which element raised the event, use the normalized event object that jQuery passes into event handlers:

$("p").bind("click", function(evt) {
  // this === evt.target;

  alert($(evt.target).text());
});

Or:

$("p").bind("click", myfunction);

myfunction(evt) {
  alert($(evt.target).text());
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜