简体   繁体   中英

How to use quotes within quotes properly

If you create an HTML element with JS using a string like the following, how can you add the extra quotes required within an onclick event? Since I have already exhausted double and single quotes, is there an elegant way of making this work?

var foo_td="<td onclick='window.open('newpage.html', '_blank')'>Open Page</td>";

You need to replace innermost single quotes ' with double quotes " and escape them with single backslash \\ , like this:

var foo_td="<td onclick='window.open(\"newpage.html\", \"_blank\")'>Open Page</td>";

Demo

Why escape quotes at first place

This is because when the onclick event will be fired on this td and if there are no quotes (if quotes not escaped), then it will look for a variable named newpage.html and _blank and give an error because these variables (most likely) won't exist.

Why not only single backslash with single quote

Single-backslash will only escape the string for the evaluation of this string expresion, and by the time this value is stored in a string it will ignore this backslash.

Why not double backslash with single quote

By the time nodes are rendered on DOM (can check this on Developer Tools of your browser), its attribute values are enclosed inside a double quote rather than a single quote. So, it will be rendered as this and hence give an error.

<div onclick="window.open(\" newpage.html\',="" \'_blank\')'="">Open Page</div>

So, based on three reasons given above you should always escape double quote if you want to pass a string parameter to a function call from an attribute .

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