我在firebug中收到此错误:
SyntaxError: missing ) after argument list
从这段代码:
table +=
'<tbody>'+
'<tr>'+
'<td>'+this.zona+'</td>' +
'<td>'+this.rruga+'<br/><div id="dialog-'+this.id+'" style= "margin-left:1px; width:340px; display:none;height:180px"></div></td>' +
'<td>'+this.dita+'</td>' +
'<td><img src="images/map.jpg" id = "mapicon" onClick="show(this.rruga, this.id);"></td>' +
'<tr>'+
'<tbody>';
我不太确定我的代码中缺少哪个括号)
。
答案 0 :(得分:5)
这是因为您在引号中使用了+
。你编码
str = '...' + 'onclick="show(' + this.rruga + ', ' + this.id + ');"' + '...';
将生成类似于
的HTMLonclick="show(hello world,foo bar);"
这显然不起作用,因为函数的参数不再被正确引用,因此被视为变量名,然后空格会引发异常。在最糟糕的情况下,您没有this.rruga
或this.id
引用或HTML编码,有人可能会传递一段特制的代码,这会将自定义HTML注入页面。
只要您对参数进行编码,就可以继续使用字符串,这样它们就是HTML安全的,不会结束引号,然后在它们周围添加引号(\'
)。
HTML + JavaScript编码引号\\"
为\"
,\\'
为\'
。前面的\\
是为了不破坏 JavaScript 引号,然后&foo;
是该字符的HTML编码。
str = '...' + 'onclick="show(\''
+ (''+this.rruga).replace(/"/g, '\\"').replace(/'/g, '\\'') + '\', \''
+ (''+this.id).replace(/"/g, '\\"').replace(/'/g, '\\'') + '\');"'
+ '...';
当您在 JavaScript 中生成所有这些内容时,请考虑将您的侦听器保留在HTML字符串之外,并使用addEventListener
或仅node.onclick
将其附加到元素。这意味着您可以继承您所需功能的范围(虽然this
仍将更改为 Node ),如果您使用DOM方法,则可以少得多通过特殊编码来担心,因为浏览器将为您完成工作。
编辑我会添加一个让您轻松的功能
function quoteAndEscape(str) {
return ''
+ ''' // open quote '
+ (''+str) // force string
.replace(/\\/g, '\\\\') // double \
.replace(/"/g, '\\"') // encode "
.replace(/'/g, '\\'') // encode '
+ '''; // close quote '
}
quoteAndEscape('I\'ll say "hello" to the WORLD!');
// 'I\'ll say \"hello\" to the WORLD!'
// which is a HTML-encoded JavaScript String literal.
// You may also want to encode the opening and closing quotes
// these ones don't need to be backslash-escaped though.
// edited that too
答案 1 :(得分:3)
我假设您发布的内容是命令的一部分,因此前面有一个'
。
如果this.rruga
有特殊字符,例如空格,则可以收到此错误消息。例如:代码将创建类似show(hello there, 12);
的语法错误。您可以通过检查生成的html内容来验证这一点。
解决方案:将该参数放在引号内。 ... \''+this.rruga+'\'
...
答案 2 :(得分:1)
你不能在''里面使用this
。
此外,您需要使用getAttribute()
才能从特定元素中获取rugga
值。
这是一个有效的fiddle。