问题
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