Bind this keyword for non-anonymous functions

Say I have the following code

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

When the user clicks the button <p>, a warning appears. Good thing I use the keyword "this".

Now I want to get rid of the anonymous function (using it several times per script);

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

Now this refers to the window. How can i fix this?

Update:

Proposed Respondent Solution That Actually Works

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

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

This is good, but you end up creating a new function every time a line of code is called, no?

+3
source share
5 answers

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

Javascript . , .

, :

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

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

:

jquery bind Jonathon , , .

, , ref.

Try

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

-

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

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

. .

+3

: ?

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

, :

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

, , .

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

jQuery

event.currentTarget

: DOM .

​​

: 1.3

.

+1
source

The problem was that your event handler calls a function myfunction(), as compared to a reference to her myfunction. This changed the scope in which he worked. If you pass a function to,, myfunction"this" will work as expected.

In general, if all you are really interested in is knowing which element raised the event, use the normalized event object that jQuery passes to the 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());
}
+1
source

Source: https://habr.com/ru/post/1732295/


All Articles