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

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - testing a function in jsfiddle

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...