views:

107

answers:

4

I've seen this done, but I can't find an example anymore. What I'd like is to switch a jQuery action... the code below is just an example, it is not the code I am using, I'm just trying to remember how this works.

var action = (getURL) ? "attr('href')" : "html()";
alert( "The result is" + $('#myLink')[action] );

I also tried

var action = (getURL) ? ".attr('href')" : ".html()";
alert( "The result is" + $('#myLink')[action] );

sorry my memory stinks and I couldn't find an example of this in the jQuery docs either. I'm not even sure if those are called "actions".

+1  A: 

Is there some reason you don't want to do this?

var result = '';
if (getURL) {
    result = $('#myLink').attr('href');
} else {
    result = $('#myLink').html();
}
alert("The result is " + result);

Or, how about:

var result = getURL ? $('#myLink').attr('href') : $('#myLink').html();
alert("The result is " + result);
TM
Well, I'm working on a jQuery plugin. And I want the user to be able to tell the script where to get some data, be it from an attribute of an element or inside a tag. It might not be the best way, but I'm tinkering and learning.
fudgey
A: 

You could do this:

alert( "The result is" + ((getURL) ? $('#myLink').attr('href') : $('#myLink').html()) );
Gumbo
+1  A: 

So you want to switch the function call?

Given that approach, you probably need two separate variables:

var action = (getURL) ? "attr" : "html";
var param = (getURL) ? 'href' : null;
alert( "The result is" + $('#myLink')[action](param));

But why not use an if statement like normal?

if (getURL)
    alert("The result is" + $('#myLink').attr('href'));
else
    alert("The result is" + $('#myLink').html());
Joel Potter
Thanks, this is what I was trying to get... function call, LOL ok I'll edit the title :P
fudgey
+1  A: 

The way to call a function when you won't know the parameter list until run time is by using apply().

var action = getUrl ? "attr" : "html";
var params = getUrl ? ['href'], [];

var $e = $('#myLink');
$e[action].apply($e.get(0), params);

The first parameter to apply is the object which will become this inside the function.

nickf
Interesting, I didn't know you could do this
fudgey