无法获得正确的 dynam 语法。以 ie 方式创建 onclick
我希望保持跨浏览器兼容性,据我所知,这是迄今为止唯一的问题。
.setAttribute("onclick", "return showRapidText("+itemnum+");");
这很完美,但我想通过将其放入此语法中来使其与 IE 兼容,
.onclick = new Function("fnDisplay_Computers('" + alines[i] + "')");
所以...我尝试了
.onclick = new Function("showRapidText('" + itemnum + "')");
大约
.onclick = new Function("return showRapidText('" + itemnum + "')");
40 种其他方法,但没有任何效果
I was hoping to keep cross-browser compatibility and afaik this is the only issue so far.
.setAttribute("onclick", "return showRapidText("+itemnum+");");
This works PERFECT but I'd like to make it IE compatible by putting it in this syntax
.onclick = new Function("fnDisplay_Computers('" + alines[i] + "')");
so... I tried
.onclick = new Function("showRapidText('" + itemnum + "')");
and
.onclick = new Function("return showRapidText('" + itemnum + "')");
and about 40 other ways but nothing works
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
+1 JP 的答案:函数文字比字符串要好得多。将字符串中的代码拼凑在一起是一件令人恐惧的事情,您应该不惜一切代价避免。另外,由于 IE 兼容性(并且因为 DOM Level 1 HTML 属性无论如何都更具可读性),所以
setAttribute
几乎不应该在 HTMLDocument 中使用。但有一个潜在的陷阱:如果您在循环中执行此操作(看起来好像是这样),则由于 闭包循环问题。您可以使用另一个闭包来解决此问题:
或者使用 ECMAScript 第五版功能
Function#bind
更干净地解决此问题:将 Function#bind 添加到尚不支持它的浏览器。
+1 J-P's answer: function literals are massively better than strings. Hacking together code in strings is a horror you should avoid at all costs. Also
setAttribute
should almost never be used in an HTMLDocument due to IE compatibility (and because DOM Level 1 HTML properties are more readable anyway).One potential trap though: if you are doing this in a loop, which it looks as if you are, you won't get the behaviour you want, due to the closure loop problem. You can solve this with another closure:
or more cleanly by using the ECMAScript Fifth Edition feature
Function#bind
:Adding Function#bind to browsers that don't yet support it.