开发者

Passing variable with JavaScript function

I am trying to pass variable though the GetDetail function below. I can pass string/number and it works properly.

But I'm una开发者_Go百科ble to pass variable

detLink.onclick = new Function ("GetDetails()");
detLink.setAttribute('onclick',"javascript:GetDetails()")


detLink.onclick = function () { GetDetails ( parameter1, parameter2, ... );  }

which is an anonymous function.

Read also The function expression (function operator)

A function expression is similar to and has the same syntax as a function declaration

function [name]([param] [, param] [..., param]) {
   statements
}

name The function name. Can be omitted, in which case the function becomes known as an anonymous function.

param The name of an argument to be passed to the function. A function can have up to 255 arguments.

statements The statements which comprise the body of the function.


detLink.setAttribute('onclick',"javascript:GetDetails("+yourVariableName+")")

When You set attribute You are using string datatype, thus you have to stitch function name with variable VALUE


If you have access to the variable in question when you set the click handler,

detLink.onclick = function() { 
  GetDetails(foo); 
}

If you don't,

detLink.id = uniqueId;
detLink.onclick = function() {
  var foo = globalData[this.id];
  GetDetails(foo);
}

// somewhere else in your code, where you know the value of the variable
globalData[detLink.id] = foo;


var val1 = "Hell world"
detLink.onclick = GetDetails( val1 );

function GetDetails( myVar ){
   alert ( myVar );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜