Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - Uncaught ReferenceError for a function defined in an onload function

HTML:

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

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);
}

Error:

Uncaught ReferenceError: cc is not defined 

Example: http://jsfiddle.net/LXSZj/3/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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

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.

For example, see this js fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...