无法获得正确的 dynam 语法。以 ie 方式创建 onclick

发布于 2024-08-30 06:10:44 字数 496 浏览 3 评论 0原文

我希望保持跨浏览器兼容性,据我所知,这是迄今为止唯一的问题。

.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回首观望 2024-09-06 06:10:44
element.onclick = function() {
    return showRapidText(itemnum);
};
element.onclick = function() {
    return showRapidText(itemnum);
};
最终幸福 2024-09-06 06:10:44

+1 JP 的答案:函数文字比字符串要好得多。将字符串中的代码拼凑在一起是一件令人恐惧的事情,您应该不惜一切代价避免。另外,由于 IE 兼容性(并且因为 DOM Level 1 HTML 属性无论如何都更具可读性),所以 setAttribute 几乎不应该在 HTMLDocument 中使用。

但有一个潜在的陷阱:如果您在循环中执行此操作(看起来好像是这样),则由于 闭包循环问题。您可以使用另一个闭包来解决此问题:

for (var i= 0; i<alines.length; i++) {
    elements[i].onclick= function(i) {
        return function() {
            fnDisplay_Computers(alines[i]);
        };
    }(i);
}

或者使用 ECMAScript 第五版功能 Function#bind 更干净地解决此问题:

for (var i= 0; i<alines.length; i++) {
    elements[i].onclick= fnDisplay_Computers.bind(null, alines[i]);
}

将 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:

for (var i= 0; i<alines.length; i++) {
    elements[i].onclick= function(i) {
        return function() {
            fnDisplay_Computers(alines[i]);
        };
    }(i);
}

or more cleanly by using the ECMAScript Fifth Edition feature Function#bind:

for (var i= 0; i<alines.length; i++) {
    elements[i].onclick= fnDisplay_Computers.bind(null, alines[i]);
}

Adding Function#bind to browsers that don't yet support it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文