Calling a javascript function via href?

I'm trying to call a javascript function (no argument) via href, it works fine, but the same function call (with an argument) via error unexpected end of input

infowindow.setContent("<table><tr><th>Name</th><td><a href='javascript:Institute('"+code+"')'>" + text + "</a></td></tr><tr><th>IP Address</th><td>" + ip + "</td></tr><tr><th>Code</th><td><a href='javascript:Institute();'>" + code + "</a></td></tr></table>");

      

+3


source to share


3 answers


This should work:

infowindow.setContent('<table><tr><th>Name</th><td><a href="javascript:Institute(\''+code+'\')">' + text + '</a></td></tr><tr><th>IP Address</th><td>' + ip + '</td></tr><tr><th>Code</th><td><a href="javascript:Institute();">' + code + '</a></td></tr></table>');

      

So the HTML result has double quotes ( "

) for tag attributes and single quotes ( '

) for JavaScript strings, which is the best way to avoid conflicts.



To demonstrate, document.write()

and are used instead alert()

, but works if you pressRun code snippet

var code = 'The Code';
var text = 'The Text';
var ip = 'The IP';

document.write('<table><tr><th>Name</th><td><a href="javascript:alert(\''+code+'\')">' + text + '</a></td></tr><tr><th>IP Address</th><td>' + ip + '</td></tr><tr><th>Code</th><td><a href="javascript:alert(\'empty string\');">' + code + '</a></td></tr></table>');
      

Run codeHide result


+2


source


You have a problem with your quote. Using:<a href='javascript:Institute(\'"+code+"\')'>



You can find it easily if you are using the HTML debugger from your web browser.

+1


source


infowindow.setContent('<table><tr><th>Name</th><td><a href="javascript:Institute(\""+code+"\");' + text + '</a></td></tr><tr><th>IP Address</th><td>' + ip + '</td></tr><tr><th>Code</th><td><a href="javascript:Institute();">' + code + '</a></td></tr></table>');

      

0


source







All Articles