jay
jay

Reputation: 117

jquery calling a function

yet again thanks for looking.

i like to call a function (eg. comment_disp, post_disp or any other i create later on).

i have created a json function with url, fname and id can i use fname as a function name?

// on document ready runs
json('comments.php','comment_disp');
json = function(url,fname,id){
$.getJSON(url,(fname));
}

comment_disp = function(json){
}

Upvotes: 2

Views: 170

Answers (2)

Andrew
Andrew

Reputation: 14526

Assuming your functions are available in the "global scope" (i.e. not written as a private member of another class/constructor), you can call your functions by string name like this:

window['comment_disp']();

This would be the equivalent of calling

comment_disp();

Upvotes: 1

Tomalak
Tomalak

Reputation: 338168

Functions are first-class objects in JavaScript. You can put them into parameters directly, no need to transport their name as string.

So instead of

json = function(url,fname,id){ $.getJSON(url,(fname)); }

do

json = function(url,f,id){ $.getJSON(url, f); }

and call it as

json('comments.php', comment_disp);

Upvotes: 2

Related Questions