JamesTBennett
JamesTBennett

Reputation: 2311

Can onclick take a function in a function?

THis is what I want.

onclick="pager(function2();)

but it doesn't seem to work.

Upvotes: 0

Views: 161

Answers (4)

Nick Craver
Nick Craver

Reputation: 630419

If you're using jQuery, please don't use in-line script, assign the click handler, like this:

$("div").click(function() {
  pager(function2());
});

This is if you wanted to assign it to all <div> elements, if you wanted it on a particular element via ID, like this: <a href="#" id="bob">Link</a>. You would use $("#bob") instead of $("div"). There's a full list of selectors here, if you're familiar with CSS, you'll feel right at home.

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

you can do something like this to make it work

<p onclick="pager(function2())">Click Me</p>


​function pager(fn)​{
    return fn;
}
  function function2(){
    alert('hello');
  }

Upvotes: 0

Ben
Ben

Reputation: 16553

This works for me

<html>
<head>
</head>
<body>
<a href="#" onclick="function2(function1());">Click me</a>
<script>
    function function2(msg) { alert(msg); };
    function function1() { return "Hello World"; };
</script>
</body>
</html>

What's not working in your code?

Upvotes: 0

Anurag
Anurag

Reputation: 141879

Take out the semicolon:

onclick="pager(function2())"

http://jsfiddle.net/BQYVV/

You are not passing a function to a function, but just a value. When the element is clicked, function2() is called, and it's return value becomes an argument to the pager() function. If function2 does not return anything, pager will receive undefined as an argument.

Upvotes: 3

Related Questions