0

Is there any way to pass the arguments to jquery/javascript like below

function showContentDiv(args ......){
 //do some thing with looping args
}

and usage like

showContent("","","","");  //should change the parma count each time 

Reason behind avoid preparing a array in jquery and passing is I have links like below

<a onclick="javaScript:showContent("val1","val2","val3")">

<a onclick="javaScript:showContent("val1","val2")">
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Or maybe it's a duplicate of [Is it possible to send a variable number of arguments to a JavaScript function?](http://stackoverflow.com/q/1959040/218196). I don't know if you are asking for how to create a variadic function or how to call one. – Felix Kling Jun 22 '13 at 13:34

2 Answers2

4

JavaScript functions automatically have an arguments object - an array-like object that includes elements for every parameter passed to the function.

The following example simply loops through any arguments and logs them to the console.

function showContentDiv(){
   for (var i = 0; i < arguments.length; i++) {
       console.log(arguments[i]);
   }
}

As an aside, don't include javaScript: at the beginning of your event attributes. This isn't required by any browser. onclick="showContent()" is fine. (Where by "fine" I mean "not as good as binding the events in a script block".)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

try this

<a onclick="javaScript:showContent("val1,val2,val3")">

function showContentDiv(args){
var argsList=args.split(',');
for(i=0;i<argsList.length;i++)
{
argsList[i]
}
 //do some thing with looping args
}
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
  • What if you want to call `showContent()` with arguments that aren't all strings? For example, `showContent({'a':1,'b':[45,12,2]}, 'test', true)` - or a less contrived example, `showContent(func1, func2, func3)` (where the arguments are function references). – nnnnnn Jun 22 '13 at 13:33