0

I am developing a mobile application using phonegap and jquery mobile. I have this function which has to pass a variable to another function. It goes something like this:

    $.each(response.records, function(i, contact) {
       var url = contact.Id;
       var newLi = $("<li><a href='javascript:dothis("+url+")'>" + (i+1) + " - " + contact.Name + " - Company "+contact.Company+"</a></li>");
           ul.append(newLi);}

I have the dothis(argument) function but it does not get called when i put in the variable "url". When i erase the argument, it works. Please Help!

user790514
  • 137
  • 1
  • 2
  • 12

2 Answers2

3

It's definitely not good practice to use the javascript: protocol in href attributes. It's much better to bind events to the links and respond accordingly.

Insert something like this after you append newLi to the ul:

$.find('a').bind('click', function() {
    dothis(url);
});

Here's some more info about why it's bad practice to use the javascript: protocol: Why is it bad practice to use links with the javascript: "protocol"?

Community
  • 1
  • 1
Philip Walton
  • 29,693
  • 16
  • 60
  • 84
1

You need to put the url in quotes in the javascript:

var newLi = $("<li><a href=\"javascript:dothis('" +
      url +
      "')\">" + 
      (i+1) + " - " + contact.Name + 
      " - Company " + contact.Company + "</a></li>");

You might need to consider escaping the URL so that, if it contains any difficult characters, your javascript won't break.

craigmj
  • 4,827
  • 2
  • 18
  • 22