0

Possible Duplicate:
How do you find out the caller function in JavaScript?

I have the following code:

JS:
function myfunc(mynumber){
   console.log(mynumber);
}

HTML:
<div onclick="myfunc(5);"></div>

Is there a way, with jQuery, to be able to get the context of that element that was clicked inside the myfunc function, without passing this or $(this) as a parameter in the onclick attribute?

Community
  • 1
  • 1
Dzhuneyt
  • 8,437
  • 14
  • 64
  • 118
  • 3
    Yes, remove the inline `onclick` function and use a proper `$(element).on('click', function() {...})` instead, and all your problems are solved. – adeneo Jan 15 '13 at 10:41
  • what are you passing in the function param? – Jai Jan 15 '13 at 10:48

3 Answers3

2
<script>
  $( "div").bind("click", function( e ) {
    myfunc(mynumber)
  });
</script>

or with param

$('div').bind("click", {  Param1: 2 }, function(event){
    alert(event.data.Param1);
});
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

I'd use jQuery to actually bind the event handler, that way this inside that function will refer to the element that triggered the event. You can use a HTML5 data-* attribute to store the number that you want to use for that particular element.

HTML

<div data-number="5">5</div>
<div data-number="26">26</div>

jQuery

$(function() {
    $('div').on('click', function(e) {
        console.log($(this).data('number'));
        console.log(this);
    });
});
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

not sure if this is what you asked for. you can call a function with

myfunc.call(params);

now in myfunc, when you refer or use this, it refers to the context or DOM it was called from.

Rahul
  • 928
  • 5
  • 8