0

Suppose I have below codes written with jquery:

  <script>
 $(function () {
        $("#btn1").click(function () { alert("OK"); });
    });
 </script>
<body>
    <input type="button" value="input" id="btn1" /><label id="lbl"></label><br />
</body>

I need get the function of btn1. The pseudo code as follows:

var f=Get_function_of_btn1("#btn1").

Then, when I call f(), it alerts "OK".

How to implement it?

BTW, can jquery print the function as string? like below:

console.log(f);

then it will print :

function () { alert("OK"); }
roast_soul
  • 3,554
  • 7
  • 36
  • 73
  • why not just use $("#btn1").click() to trigger the function on command? – Buck3y3 Jan 09 '15 at 15:10
  • I know use $("#btn1").click() is OK, but I wonder is there another solution. – roast_soul Jan 09 '15 at 15:11
  • Looks like this is probably a duplicate of http://stackoverflow.com/questions/9046741/get-event-listeners-attached-to-node-using-addeventlistener – Joel Lee Jan 09 '15 at 15:13
  • Check http://stackoverflow.com/questions/9086106/get-value-of-current-event-handler-using-jquery – LS_ᴅᴇᴠ Jan 09 '15 at 15:24
  • Here is the true duplicate: http://stackoverflow.com/questions/6583330/javascript-object-get-code-as-string also see my comment to Rory M.'s answer. – Buck3y3 Jan 09 '15 at 15:30

3 Answers3

1

Define your function in the standard manner with an identifier:

function foo() {
    alert('OK');
}

You can then assign this function to the click() handler and retrieve it in a console.log (not that I see the point of the latter):

$(function () {
    $("#btn1").click(foo);
});

console.log(foo);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

you could call the function from the button itself:

<input type="button" value="输入" id="btn1" onclick='f();' />
function f(){
    alert("ok");
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
M Reza Saberi
  • 7,134
  • 9
  • 47
  • 76
0

You can assign function to variables too:

var f = function(){
    alert('ok');
}
f();

Example

For the console-ouput you can use:

console.log(f.toString());

Thanks @Buck3y3 for the hint

empiric
  • 7,825
  • 7
  • 37
  • 48