onload函数中定义的函数的未捕获的ReferenceError [英] Uncaught ReferenceError for a function defined in an onload function

查看:1411
本文介绍了onload函数中定义的函数的未捕获的ReferenceError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<div id="myID" onclick="cc(this.id)">Click Here</div>​

JavaScript:

JavaScript:

var timer;
var firing = false;
var begen = function(id) {
    alert('tek');
};

var popupAc = function(id) {
    alert('çift');
};

function cc(id) {
    if (firing) {
        popupAc(id);
        clearTimeout(timer);
        firing = false;
        return;
    }
    firing = true;
    timer = setTimeout(function() {
        //begen(id);
        clearTimeout(timer);
        firing = false;
    }, 250);
}

错误:

Uncaught ReferenceError: cc is not defined 

示例: http://jsfiddle.net/LXSZj/3/

推荐答案

您的JSFiddle首选项设置为onload,因此JavaScript窗格的内容包含在一个函数中。

Your JSFiddle preferences are set to "onload", so the content of the JavaScript pane is wrapped in a function.

此范围 cc dd 不存在,为jsfiddle创建了一个额外的问题示例)到该函数并停止它是一个全局。

This scopes cc (dd does not exist, creating an additional problem for the jsfiddle example) to that function and stops it being a global.

因为你试图从一个内部事件属性调用它,你在不同的范围内,无法访问它。

Since you are trying to call it from an intrinsic event attribute, you are in a different scope and cannot access it.

作为快速修复,您可以将首选项更改为nowrap,但这不会使代码符合最佳实践。

As a quick fix, you can change the preference to 'nowrap', however that won't make the code conform to best practises.

建议避免使用内部事件属性来支持使用Javascript绑定事件处理程序。 YUI3提供事件模块,jQuery提供 on 方法以帮助解决此问题(其他库可用)。另请参阅:不引人注目的JavaScript

It is recommended to avoid intrinsic event attributes in favour of binding event handlers with Javascript. YUI3 provides an event module and jQuery provides the on method to help with this (other libraries are available). See also: Unobtrusive JavaScript.

例如,看到这个js小提琴

这篇关于onload函数中定义的函数的未捕获的ReferenceError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆