calling a variable as if it was a function

K

k.j.stellema

I wonder if this is possible.. i have a couple of anchors inside a
page and all have 'pretty' URLs in the form of 'foo/bar/' and 'foo/
béar/'. If the user clicks on such an anchor (they are buttons) i
don't want them to navigate there but instead i wish a javascript
function te be executed... not that difficult huh?

however i noticed that each of my urls is guarenteed to be unique and
i wish to have for the url '/foo/bar/' an action called foobarAction.
For '/foo/bear' i want it to be foobearAction.. but lazy as i am i
don't want to write a seperate onclick handler for each element.

So what i basically wish to accomplish is to read the 'href' part (/
foo/bear/) get rid of the slashes (as i am in FF 2.0 it's just /foo/
bear/ btw i am aware that in other browsers this could become
http://mysite.com/foo/bear) and call it as were it a function..

The part to read the contents of the href is easy, getting rid of the
slashes and concatenating it to a string is also easy. I setup a nice
function with exactly the same name (yep.. checked 3 times i didnt
make typos) and then called the function.. and it says it doesnt
exist :(

I tried this:

function foobarAction () {alert ('hello world!');}

method = <content of href of <a href="/foo/bar">click me</a> +
'Action';
method();

and

foobarAction = function foo () {alert ('hello world!');
method = <content of href of <a href="/foo/bar">click me</a> +
'Action';
method();

both times no 'hello world' :(

I am now thinking such a cast from a variable to a function or
'calling a variable' in this paticular way cannot be done. Am i
right??

Thanks in advance
 
R

Randy Webb

(e-mail address removed) said the following on 2/21/2007 4:18 PM:

I am now thinking such a cast from a variable to a function or
'calling a variable' in this paticular way cannot be done. Am i
right??

No, you are not right.

functionToCall = <content of href of...> + "Action";
window[functionToCall]();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top