简体   繁体   English

如何转义作为参数传递的字符串——无效的语法。 缺少 ) 参数列表后

[英]How to escape string getting passed as parameter -- Invalid Syntax. Missing ) after argument list

I keep getting this error when trying to use jquery append.尝试使用 jquery 附加时,我不断收到此错误。

Uncaught SyntaxError: missing ) after argument list

Here is my code:这是我的代码:

$(".grid-uniform").append('<input type="checkbox" id="addToCompare-'+prod.id+'" class="addToCompare" onclick="addProductToCompare('+prod.id+','+prod.json.variants[0].id+','+prod.title+')">');

Here are the values being passed in:以下是传入的值:

addProductToCompare(1557908979773,13234446893117,Apple iPhone X - Zizo ION Triple Layered Hybrid Rugged Case with Tempered Glass, Smoke/Clear)

It looks like the 'with' in the string is getting picked up as JavaScript.看起来字符串中的 'with' 被作为 JavaScript 接收了。 It should just be a string.它应该只是一个字符串。 When I check typeof it returns string.当我检查 typeof 它返回字符串。 If I swap prod.price instead of prod.title though and keep everything else the same, it works fine.如果我交换 prod.price 而不是 prod.title 并保持其他所有内容相同,它就可以正常工作。

It is because you don't make the third argument a string literal, delimiting with quotes.这是因为您没有将第三个参数设为字符串文字,并用引号分隔。

$(".grid-uniform").append(
    '<input type="checkbox" id="addToCompare-'+prod.id+'" class="addToCompare" ' +
    'onclick="addProductToCompare('+prod.id+','+prod.json.variants[0].id+',\''+prod.title+'\')">'
);

Note the added \\' around the last argument.注意最后一个参数周围添加的\\'

The better way to do this:更好的方法是:

$(".grid-uniform").append(
     $('<input>').attr({type: "checkbox", id: "addToCompare-"+prod.id})
         .addClass("addToCompare")
         .click(function () {
              addProductToCompare(prod.id, prod.json.variants[0].id, prod.title);
         })
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM