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

admin2025-03-31  9

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

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/LXSZj/3/

Share Improve this question edited Sep 7, 2012 at 12:36 Gilles 'SO- stop being evil' 108k38 gold badges215 silver badges260 bronze badges asked Sep 7, 2012 at 12:26 AliRıza AdıyahşiAliRıza Adıyahşi 15.9k24 gold badges118 silver badges197 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

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 remended 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.

It does, you just have two errors in your fiddle:

  • You called dd instead of cc
  • You wrapped your whole javascript in a onload-function (see dropdown on the left), and the variables and functions are local to that. Move it to the global scope, or assign the cc function to the global object: window = function(){…};

Corrected version

window = function(id) { ...

the variables and functions seem to be in their on scope...

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743352710a213000.html

最新回复(0)