简体   繁体   中英

onclick attribute doesn't find global function

I dinamically add divs with onlick event, but clicking got an error (Mozilla Firefox): "ReferenceError: myfoo is not defined". If I change onclick event to alert, it works fine, but non with mysefl written functions.

Here is jsfiddle

http://jsfiddle.net/UJ85S/5/

function myfoo(x)
{
    alert(x);
}

$("#some").html('<div id="cool_div" onclick="myfoo('+"'xwe'"+');"></div>');

Can you, please, explain what is wrong? (I understant that can assign.click event, but is it possible through onclick?).

What you really need to do is not let jsFiddle wrap it inside the onload event as this uses a function which creates new scope. Your function is then not accessible outside this new scope. Learn what's happening not learn how to get around it (ie not just hack your code to the window Object):

http://jsfiddle.net/UJ85S/12/

No wrap - in <body>

This is happening because you define myfoo inside of $(window).load(function () {...}) function (JSFIDDLE does this):

You need to declare a global function. You can do window.myfoo to declare your function instead.

window.myfoo = function (x)
{
    alert(x);
}

JSFIDDLE

But yeah, it's not a good practice to polute the global scope, that's why it's better to use $(...).on("click", function () { alert(...) }) handlers.

I discourage using on... attributes in HTML because it's also another bad practice .

Your code becomes:

function myfoo (x)
{
    alert(x);
}

var $divToAppend = $("<div id='cool_div'>")
$divToAppend.on("click", function () {
    myfoo("hello");
});

$("#some").html($divToAppend);

And here a DEMO .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM