Js assignment contains a solution to the problem of single and double quotes

  • 2020-03-30 02:09:16
  • OfStack

My page is a JSP page, which contains a parameter: lefttree,

This lefttree is spelled out from the background, the content is HTML code: such as:
 
<div class="test" onclick="show('tt1','abc')"> 

In the JSP page, you need to pass the value to a div through the js code, as follows:
 
<script type="text/javascript"> 
window.parent.document.getElementById('mptree').innerHTML='<%=lefttree%>'; 
<script> 

In this way, because lefttree contains both single and double quotation marks, there is an error in matching with the outermost single quotation mark in js, and it becomes:
 
'<div class="test" onclick="show('tt1','abc')">' 

Solutions:

Escape character "/"

When splicing lefttree in the background, it becomes the following form:

 
<div class="test" onclick="show(///'tt1///',///'abc///')"> 

Among them:

The first two "//" s are used to leave a "/" in the page

The third "/" escapes the single quote after it.

In this way, the value of lefttree is:
 
<div class="test" onclick="show(/'tt1/',/'abc/')"> 

Related articles: