Am I incorrectly avoiding strings in JavaScript?

I am trying to create a clickable link in javascript

var content = '<a href=\"#\" onclick=\"displayContent(\"TEST\")\">Whatever</a>'; $("#placeHolder").html(content); 

but I still get the error message

Untrained SyntaxError: Unexpected Token}

Is this not the right way to escape double quotes and create a link?

+6
source share
4 answers

You only need to avoid single quotes

 var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>' 

As bozdoz says:

You avoid single quotes that are in single quotes; you avoid double quotes that are enclosed in 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') }); 
+7
source

You can avoid this mess by creating these elements:

 var content = $( "<a>", { href: "#", text: "whatever", click: $.proxy( displayContent, 0, "TEST" ) }); 
+2
source

You only need to escape quotes when they are the same type as your open and close quotes. In your example, you do not necessarily avoid double quotes because your string is enclosed in single quotes. At the same time, due to double quotes in the onclick expression, the parser will have problems calling displayContent() .

Try this instead:

 var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>'; 
+1
source

You do not need to avoid them at all!

 var content = '<a href="#" onclick="displayContent(\'TEST\')">Whatever</a>'; $("#placeHolder").html(content); 

Just keep this as you don’t need to avoid " usually when it’s embedded in ' ;

But you need to avoid the characters ' when it is a parameter in a function.

0
source

Source: https://habr.com/ru/post/906238/


All Articles