How to use function declaration with jsfiddle

2019-06-26 11:15发布

I have some html/javascript that works in my .cshtml file.
When I try to move it in to jsfiddle to experiment with, it does not work.
Not sure if if it's my lack of javascript experience, jsfiddle experience, probably both....

html:

<div>
<button name="startBtn" id="startBtn" onclick="startTimer">Start</button>
</div>  

(I have also tried "startTimer()" for the onclick attribute; same result.)

javascript:

function startTimer() { alert("startTimer"); }

When I click the button, I see this in the Console:

Uncaught ReferenceError: startTimer is not defined

What am I overlooking?
(jsfiddle: http://bit.ly/1buQx9t)

6条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-26 11:41

First issue: You have the jsfiddle to set on onload so the function is not in global scope.

enter image description here

Second issue, you are not calling the function. You are missing ()

 onclick="startTimer()"
查看更多
不美不萌又怎样
3楼-- · 2019-06-26 11:41

You had some extra misplaced quotes and were not calling the function. Needed to add the () to call it. Finally you needed to change the "onload" to "no wrap - in "

<div>
     <input type="button" value="Start" onclick="startTimer()"/>
 </div>
查看更多
来,给爷笑一个
4楼-- · 2019-06-26 11:42

You have some weird quotes going on there (in your fiddle) plus you forgot the () after the name of the function. Use:

<input type="button" value=" Start " onclick="startTimer()" />

jsFiddle example

查看更多
地球回转人心会变
5楼-- · 2019-06-26 11:47

jsFiddle Demo

First you have to set the Framework to No wrap - in <head>, instead of onLoad.

JSFiddle Option

Description

onLoad is the same as window.onload=function(){[YOU ARE TYPING HERE]} in JavaScript or $(function(){[YOU ARE TYPING HERE]}); in jQuery.

No wrap - in <head> is the same as <head><script type="text/javascript">[YOU ARE TYPING HERE]</script</head>

No wrap - in <body> is the same as <body>[HTML CODE HERE]<script type="text/javascript">[YOU ARE TYPING HERE]</script></head>

I hope this clears up the settings in jsFiddle, they can be somewhat confusing.


Second your HTML is slightly wrong:

HTML

<div>
    <input type="button' value='"Start" onclick="startTimer()"/>
</div>

Description

onclick="startTimer" was changed to onclick="startTimer()" this will execute the function.

查看更多
虎瘦雄心在
6楼-- · 2019-06-26 11:48

If you're using pure JavaScript in jsfiddle (ie - no jquery, etc), then change the second dropdown to "No wrap - in <head>"

查看更多
时光不老,我们不散
7楼-- · 2019-06-26 11:54

The answers above are all right; I just wanted to clarify what/where to change with this picture to solve the issue:

Here is the jsfiddle demo

<button onclick="doThat()">
Click
</button>

function doThat() {
    console.log("click happened");
}

enter image description here

查看更多
登录 后发表回答