【问题标题】:Is there any way to pass multiple arguments to jquery function [duplicate]有没有办法将多个参数传递给jquery函数[重复]
【发布时间】:2013-06-19 12:44:24
【问题描述】:

有什么方法可以将arguments 传递给jquery/javascript,如下所示

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

和类似的用法

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

避免在 jquery 中准备数组并传递的原因是 我有如下链接

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

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

【问题讨论】:

标签: javascript jquery function web-applications arguments


【解决方案1】:

JavaScript 函数自动有一个 arguments object - 一个类似数组的对象,其中包含传递给函数的每个参数的元素。

以下示例简单地遍历所有参数并将它们记录到控制台。

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

顺便说一句,不要在事件属性的开头包含javaScript:。任何浏览器都不需要这样做。 onclick="showContent()" 很好。 (这里的“好”是指“不如在脚本块中绑定事件”。)

【讨论】:

  • 这看起来很棒,让我继续努力。
【解决方案2】:

试试这个

<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
}

【讨论】:

  • 如果你想用不是所有字符串的参数调用showContent()怎么办?例如,showContent({'a':1,'b':[45,12,2]}, 'test', true) - 或者一个不那么做作的例子,showContent(func1, func2, func3)(其中参数是函数引用)。
猜你喜欢
  • 2020-04-15
  • 2022-01-03
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
相关资源
最近更新 更多