Bob
Bob

Reputation:

Convert some JavaScript to JQuery

I have some JavaScript code that does the following

link.NavigateUrl = string.Format("javascript:MyFunction({0}, {1});", ID1, ID2);

So when the link is click MyFunction will be called and the dynamic parameters will be passed in.

How can I pass in these parameters using jQuery like:

$(function(){
    $('#MyLinksID').click(function(){
        console.log('Want to have access the two params here');       
});

So how can I access the params from within my click event?

Upvotes: 0

Views: 236

Answers (3)

Mr.ElectroNick
Mr.ElectroNick

Reputation: 121

The problem is that click event for #MyLinksID you're referring, have no connection to the NavigateUrl property. You need to clarify your question as two guys answered 2 possible answers.

Upvotes: 0

Matthew Marshall
Matthew Marshall

Reputation: 5883

You need to use a 'closure', a central concept in javascript.

In short, a function has accesses to variables in the scope that it was created.

$(function(){
    var ID1 = 'foo';
    var ID2 = 'bar';
    $('#MyLinksID').click(function(){
        console.log(ID1+ID2);
    }
});

The ID1 and ID2 variables are in the same scope that your callback function is created in, so it can still access them when it is called later.

Upvotes: 3

Chris Hynes
Chris Hynes

Reputation: 10239

If you're trying to have MyFunction called and get access to the parameters inside the JQuery click event as well, the easiest way is to parse the href of the link.

Something like this should work (inside your jQuery click event):

var href = this.href;
var startPos = href.indexOf("(") + 1;
var endPos = href.indexOf(")");

var parms = href.substr(startPos, endPos - startPos).split(",");

Upvotes: 0

Related Questions