简体   繁体   中英

How to format an anchor tag as a string?

this line:

return '<a href="javascript:SomeFunction('+ var1 + ',' + var2 + ')"; > Stars </a>';

renders this:

<a href="javascript:SomeFunction(Pure Magic,4)" ;=""> Stars </a>

which looks like a proper anchor tag but gives this error on clicking it:

Uncaught SyntaxError: missing ) after argument list

I am sure this error is misleading as the bracket in question is right there.

What am I missing?

Thanks in advance.

As var1 contains a string value, you need quotes around it:

return '<a href="javascript:SomeFunction(\'' + var1 + '\',' + var2 + ');"> Stars </a>';

If the string can contains characters that needs to be escaped to be in a string literal, or needs to be URI encoded, you need some more code:

return '<a href="javascript:' + encodeURIComponent('SomeFunction(\'' + var1.replace("\\", "\\\\").replace("'", "\\'") + '\',' + var2 + ');') + '"> Stars </a>';

Generating code like this is complicated, and it's easy to get it wrong. If possible you should generate elements instead, so that you can set the properties directly instead of creating code for it. Example using jQuery:

return $('<a>', { href: '#', text: ' Stars ' }).click(function(e){
  e.preventDefault();
  SomeFunction(var1, var2);
});

您在双引号结尾有误

return '<a href="javascript:SomeFunction('+ var1 + ',' + var2 + ');" > Stars </a>';

You are not wrapping your first var (which seems to be a string) within quotes.

return '<a href="javascript:SomeFunction(\''+ var1 + '\', ' + var2 + ');" > Stars </a>';

NOTE : As pointed out in the comments by Paul S. the semicolon should be inside the double quotes as it is part of the attribute value.

As you just want to add an <a> with a href , let the browser do the escaping and encoding work for you by using a method like String.prototype.link

' Stars '.link('javascript:SomeFunction(' + JSON.stringify(var1) + ', ' + JSON.stringify(var2) + ')');
// <a href="javascript:SomeFunction(&quot;Pure Magic&quot;, 4)"> Stars </a>

If you're running into issues like this a lot, consider whether it would be easier to switch to working with DOM methods , ie

var a = document.createElement('a');
a.addEventListener('click', SomeFunction.bind(a, var1, var2));

This saves you from having to write entity encodings etc to protect yourself at each level the code will be interpreted ( JavaScript , HTML , JavaScript ) and means you have more direct access over the DOM tree than by writing HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM