views:

154

answers:

3

Hi all,

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 params using JQery 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?

A: 

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(",");
Chris Hynes
+2  A: 

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.

Matthew Marshall
A: 

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.

Mr.ElectroNick