I am trying to create a clickable link in javascript
var content = '<a href=\"#\" onclick=\"displayContent(\"TEST\")\">Whatever</a>';
$("#placeHolder").html(content);
but I keep getting an error
Uncaught SyntaxError: Unexpected token }
Is that not the correct way to escape double quotes and create a link?
A string contains a literal character that is a reserved character in the Regex class (for example, the '(' or open parentheses character). Placing a '\' (backslash) in front of the character in the regular expression generates an 'Invalid escape sequence' compilation error.
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
The only characters you normally need to worry about in a javascript string are double-quote (if you're quoting the string with a double-quote), single-quote (if you're quoting the string with a single-quote), backslash, carriage-return (\r), or linefeed (\n).
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
You only need to escape the single quotes
var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>'
As bozdoz says:
You escape single quotes that are within single quotes; you escape double quotes that are within double quotes
But why not do
var content = $("<a />").attr("href", "#").text("Whatever").click(function(){
displayContent('TEST')
});
Or as Nathan says:
var content = $('<a href="#">Whatever</a>').click(
function() { displayContent('TEST')
});
You can avoid that mess by creating elements like this:
var content = $( "<a>", {
href: "#",
text: "whatever",
click: $.proxy( displayContent, 0, "TEST" )
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With