Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Sorry, really stupid question here. If you post a question about javascript or jquery, people often say - create a jsfiddle.

So, I did. My question will be about getting divs to slide up using jquery but, I can't even get a basic javascript function to run in jsfiddle.

http://jsfiddle.net/ubq6E/

<div onclick="showit()">Hello</div>
function showit()
{
alert('hi');
}

A div, click on it to call a javascript function, but jsfiddle says the function is not defined. Can you not do this in jsfiddle?

See Question&Answers more detail:os

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

1 Answer

You've selected the default onLoad option in jsfiddle.

This causes the site to wrap your entire code within a callback function, meaning that your showit function is not a global function as required by DOM0 inline event handlers.

There are several work arounds, in my personal order of preference:

  1. don't use DOM0 inline handlers, they're really old school - look into element.addEventListener() instead and separate your markup from your JS.

  2. use window.showit = function() { ... } instead to force your function to appear in the global name space.

  3. select one of the "no wrap" options


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...