简体   繁体   中英

JavaScript escape '," characters

I am facing problems with escape ' character inside the onclick of an a tag

I have tried surrounding the string with double and single quotes. But I still face the issue

for(i in result.MenuItems){
var itemName = result.MenuItems[i].name;
html+=  "<a onclick=return \'itemDescr(\""+itemName+"\",\""+restName+"\")\'>"+
'
<div>
   ' +
   '
   <div>
      '+
      '
      <div style="float:left;width:50%;">
         <h3 style="color:orange">'+itemName+'</h3>
      </div>
      '+
      '
   </div>
   '+
   '
</div>
'+
'</a>';
}
html+='</div>';

Problem area in the above code: html+= ""+ ' say if eiter name or rest name have ' then the code breaks during actual invocation of that function

The final html looks like::


::html::  <div id="items"><h1>Items</h1><a onclick=return
 'itemDescr("Pho","Panda Garden")'><div><div><div
 style="float:left;width:50%;"><h3
 style="color:orange">Pho</h3></div></div></div></a><a onclick=return
 'itemDescr("Chinese Dumplings","Panda Garden")'><div><div><div
 style="float:left;width:50%;"><h3 style="color:orange">Chinese
 Dumplings</h3></div></div></div></a><a onclick=return
 'itemDescr("Gyoza","Panda Garden")'><div><div><div
 style="float:left;width:50%;"><h3
 style="color:orange">Gyoza</h3></div></div></div></a><a onclick=return
 'itemDescr("Stinky Tofu","Panda Garden")'><div><div><div
 style="float:left;width:50%;"><h3 style="color:orange">Stinky
 Tofu</h3></div></div></div></a><a onclick=return 'itemDescr("Veggie
 Burger","Panda Garden")'><div><div><div
 style="float:left;width:50%;"><h3 style="color:orange">Veggie
 Burger</h3></div></div></div></a></div>

When I click on one of the a tags I get below error:

Uncaught SyntaxError: Invalid or unexpected toke

itemDescr("Lamb Curry","Andala

It should have been :

itemDescr("Lamb Curry","Andala's");

You can put a backslash before every quote in the strings as follows:

restName = restName.replace(/'/g,"\\'");
for(i in result.MenuItems){
   var itemName = result.MenuItems[i].name;
   itemName = itemName.replace(/'/g,"\\'");

You can also use the concat() method to add strings:

let html = "<div>";
for(i in result.MenuItems) {
var itemName = result.MenuItems[i].name;
html = html.concat(
"<a onclick=return 'itemDescr(\"", 
itemName, 
'","', 
restName, 
"\")'>",
'<div>' +
    '<div>' +
        '<div style="float:left;width:50%;">' + 
            '<h3 style="color:orange">', 
                itemName,
            '</h3>' +
         '</div>' +
     '</div>' +
'</div>' +
'</a>');
}
html+='</div>';

Or you can still use the + operator. What you have to put in mind is that you do not need to escape single quotes inside double quotes nor double quotes inside single qoutes. For instance:

var d = "'hi'"; // OK: d is 'hi'
var d = "\'hi\'"; // WRONG: unnecessary escape

There's a few reasons we'd all avoid doing it the way you'd started. Maintainability and conciseness are my biggest bug-bears.

I've stashed info away using the dataset API, I've used css instead of inline styles, I've attached proper event handlers and have the handler retrieve the info from the element, rather than the element passing the info to the handler.

<!doctype html>
<html lang='en'>
<meta charset='utf-8'>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
function newEl(tag){return document.createElement(tag)}

var menuItems = [
                    { item: 'Pho', restaurant: 'Panda Garden' },
                    { item: 'Chinese Dumplings', restaurant: 'Panda Garden' },
                    { item: 'Gyoza', restaurant: 'Panda Garden' },
                    { item: 'Stinky Tofu', restaurant: 'Panda Garden' },
                    { item: 'Vege Burger', restaurant: 'Panda Garden' }
                ]

window.addEventListener('load', onLoaded, false);


function onLoaded(evt)
{
    menuItems.forEach( 
                        function(menuItem)
                        {
                            let result = newEl('a');
                            result.dataset.item = menuItem.item;
                            result.dataset.restaurant = menuItem.restaurant;

                            result.addEventListener('click', onClicked, false);

                            var div1=newEl('div'),div2=newEl('div'),div3=newEl('div');
                            let h3 = newEl('h3');
                            h3.textContent = menuItem.item;

                            div1.appendChild(div2);
                            div2.appendChild(div3);
                            div3.appendChild(h3);
                            result.appendChild(div1);
                            document.body.appendChild(result);
                        }
                    );
}

function onClicked(evt)
{
    alert(`You chose ${this.dataset.item} from ${this.dataset.restaurant}`);
}
</script>
<style>
a > div > div > div
{
    float: left;
    width: 50%;
}
h3
{
    color: orange;
}
</style>
</head>
<body>
</body>
</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