Why is JsFiddle giving not defined error?

大城市里の小女人 提交于 2019-12-25 20:04:32

问题


Take a look at this fiddle http://jsfiddle.net/fXfSz/:

If you look in the console it shiftLeft is undefined but it is defined like so:

function shiftLeft()
{
    for (var char in $('#chars').children())
    {
        log(char);
        char.css({left:char.position().left -100});
    }
}

回答1:


Your shiftLeft function isn't defined in the global scope but in the one of the onload event handler.

Remove it from the onload function code and change the fiddle wrapping setting to "no wrap - in head". Or, better, bind it using the click function.

But you have other bugs in your function. Maybe you want this :

<button id="idofthebutton">Left</button>
<script>
$('#idofthebutton').click(function(){
    $('#chars').children().each(function(){
         $(this).css({left:$(this).position().left -100});
    });
});
</script>

Demonstration




回答2:


Because the function shiftLeft is not defined in the global scope. It is local to the function that you assign to onload (a function that never runs because you have configured JSFiddle to only run the function that does that assignment onload too).

Bind your event handlers with JavaScript, not with onclick attributes.

function shiftLeft()
{
    for (var char in $('#chars').children())
    {
        // log is not a global
        console.log(char);
        char.css({left:char.position().left -100});
    }
}

function assignHandlers() {
    document.querySelector('button').addEventListener('click', shiftLeft);
}


// If you weren't using JSBin to run this onload:
// addEventListener('load', assignHandlers);
// but since you are:
assignHandlers();


来源:https://stackoverflow.com/questions/18770009/why-is-jsfiddle-giving-not-defined-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!