3
$('a').live('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, marker2); // I need instead of 2 to print the value of variable id
});

How can I dynamically change the number 2 to variable ID ?

Thanks for any help

5 Answers 5

10

Don't use eval, use a hash:

var markers = {
    "key1": function(){},
    "key2": function(){},
    "key3": function(){}
};

$('a').live('click',function(e){
    e.preventDefault();
    var id = this.id; //Use this.id instead of attr
    infowindow2.open(map, markers[id]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

lol, Dennis, i was 7 seconds faster than you )) identical answers
6

Instead of using eval, - better change you data structures:

var  markers = {
    '1': function () { doStuff(); },
    '2': function () { doOtherStuff(); },
}
$('a').live('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, markers[id]);
});

Comments

0

I think it would be easier to write a new function with a switch. I can't recommend using eval.

Comments

0

EVAL should always be the last option

In order use dynamic name in a function names you can windows object.

Here is an Example:

var id = '2';
function map2() {
    alert('me called');
}
window["map"+id]();

Demo

Your Usage would be something like this

$('a').on('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, window['map'+id]()); 
});

Comments

-2
$('a').live('click',function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    infowindow2.open(map, eval('marker' + id)); 
});

LIVE DEMO

Notes:

  • eval is deprecated, You should look for a better design.
  • so as live... You should use on instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.