函数(..)抛出'eval is evil'消息

pat*_*mer 4 javascript eval jslint

我没有使用eval,我不确定Crockford的问题是什么.有没有更好的办法来解决以下问题或者这只是我需要忽略(我喜欢完美的/改善我的解决方案,如果有需要改进的地方).

我正在使用一些像素跟踪的东西,在这种情况下,客户端已将JS函数绑定到onclickHTML图像标记的属性,该标记重定向网站.我需要可靠地跟踪点击次数,而不会遇到图像上有多个事件侦听器的竞争条件.策略是在运行时覆盖事件,在我自己的函数中复制和运行它.请注意,这适用于我无法控制且无法更改的网站.所以解决方案看起来像:

...
func = Function(img.attr('onclick'));
...
img.attr('onclick', '');
... //some custom tracking code
func.call(this);
Run Code Online (Sandbox Code Playgroud)

并且JSLint检查程序抛出eval is evil错误.

有没有更好的方法来避免围绕href行动的多个事件的竞争条件?

Aln*_*tak 7

你是隐式使用的,eval因为你要求回调函数,因为它在HTML中被指定为一个字符串属性,然后Function用它构造一个.

只需使用该img.onclick 属性,您将直接从属性中获取浏览器构建的功能,然后您可以.call:

var func = img.onclick; // access already compiled function
img.onclick = null;     // property change updates the attribute too

... // some custom tracking code

func.call(img, ev);     // call the original function
Run Code Online (Sandbox Code Playgroud)

或者更好的是:

(function(el) {
    var old = el.onclick;
    el.onclick = function() {
        // do my stuff
        ..
        // invoke the old handler with the same parameters
        old.apply(this, arguments);
    }
})(img);
Run Code Online (Sandbox Code Playgroud)

后一种方法的优点有两个方面:

  1. 它不会创建新的全局变量 - 所有内容都隐藏在匿名闭包中
  2. 它确保使用与提供给替换函数完全相同的参数调用原始处理程序