如何为JavaScript变量包裹单引号?解决语法报错问题
为JavaScript变量包裹单引号的语法修正方法
问题场景
我需要给代码中变量attribute的外层添加单引号,尝试修改Line A处代码为'${attribute}'时,触发语法错误:Uncaught SyntaxError: missing ) after argument list,原代码如下:
function deleteAttribute(attribute) { if(confirm('Are you sure you want to delete \`'${attribute}'\` ?')){ // Line A jQuery.ajax({ url: 'abc.php', type: 'post', data: { attribute: attribute }, }); } }
错误原因
你错误地在单引号包裹的普通字符串中使用了模板字符串的${}语法——只有用反引号(`)包裹的模板字符串才支持变量插值,因此导致语法冲突。
修正方案
方案1:使用模板字符串(推荐)
将整个confirm的参数用反引号包裹,直接在其中插入变量并添加单引号,同时转义原本需要保留的反引号:
function deleteAttribute(attribute) { if(confirm(`Are you sure you want to delete \`'${attribute}'\` ?`)){ // Line A 修改后 jQuery.ajax({ url: 'abc.php', type: 'post', data: { attribute: attribute }, }); } }
方案2:使用字符串拼接
如果不想用模板字符串,可以通过加号拼接字符串,注意转义单引号:
function deleteAttribute(attribute) { if(confirm('Are you sure you want to delete `\'' + attribute + '\'` ?')){ // Line A 修改后 jQuery.ajax({ url: 'abc.php', type: 'post', data: { attribute: attribute }, }); } }
内容的提问来源于stack exchange,提问作者flash
相关产品推荐
相关产品推荐

