Why is my jsfiddle Javascript class not defined?

2019-08-05 14:45发布

HTML:

<img src="https://help.pace.edu/helpdesk/info_icon_small.gif?v=12_1_0_300.gif" onclick="plusButton_Click()">

js:

function plusButton_Click() {  
    alert('hi');    
}

http://jsfiddle.net/uEypH/1/

I might be new to Javascript and all. But why does my Firefox console say

"ReferenceError: plusButton_Click is not defined"?

3条回答
贼婆χ
2楼-- · 2019-08-05 15:16

By default, jsFiddle places your Javascript code into an onLoad function. Your plusButton_Click will not be visible outside of this closure.

To fix, either:

  • Select "In <head>" from the dropdown (Example)
  • Define your function as window.plusButton_Click = function() { ... } (Example)
查看更多
疯言疯语
3楼-- · 2019-08-05 15:22

Because the function must be in global scope if you intend to call it in inline js.

jsfiddle creates a new closure, so it is not global. Use their --wrap it in head-- option.

Updated demo

Or change

function plusButton_Click() {  
    alert('hi');    
}

to:

window.plusButton_Click = function(){
   alert('hi');
}
查看更多
等我变得足够好
4楼-- · 2019-08-05 15:37

You have javascript set to onLoad. In a normal page, you would have put it straight in the body most likely. Set it to NoWrap and it should work fine.

查看更多
登录 后发表回答