Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...