Lul*_*zim -2 javascript syntax-error
我在firebug中收到此错误:
SyntaxError: missing ) after argument list
Run Code Online (Sandbox Code Playgroud)
从这段代码:
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>';
Run Code Online (Sandbox Code Playgroud)
我不太确定)我的代码中缺少哪个括号.
这是因为您使用了+引号.你编码
str = '...' + 'onclick="show(' + this.rruga + ', ' + this.id + ');"' + '...';
Run Code Online (Sandbox Code Playgroud)
将生成看起来像的HTML
onclick="show(hello world,foo bar);"
Run Code Online (Sandbox Code Playgroud)
这显然不起作用,因为函数的参数不再被正确引用,因此被视为变量名,然后空格会引发异常.在最糟糕的情况下,您没有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, '\\'') + '\');"'
+ '...';
Run Code Online (Sandbox Code Playgroud)
当您在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
Run Code Online (Sandbox Code Playgroud)