为什么我的JavaScript不能在JSFiddle中工作? [英] Why isn't my JavaScript working in JSFiddle?

查看:95
本文介绍了为什么我的JavaScript不能在JSFiddle中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到这个 JSFiddle 有什么问题。

I can't find out what is the problem with this JSFiddle.

HTML:

HTML:

<input type="button" value="test" onclick="test()">

JavaScript:

JavaScript:

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

点击按钮 - 什么都没有发生。控制台显示test not defined

And when I click on button - nothing happened. The console says "test not defined"

我读过JSFiddle文档 - 它说JS代码被添加到< head> 和HTML代码被添加到< body> (所以这个JS代码早于html并且应该可以工作)。

I've read the JSFiddle documentation - there it says that JS code is added to <head> and HTML code is added to <body> (so this JS code is earlier than html and should work).

推荐答案

该函数正在负载处理程序中定义,因此处于不同的范围。作为注释中的@ellisbben注释,您可以通过在窗口对象中显式定义它来解决此问题。更好的是,将其更改为不加引号地将处理程序应用于对象: http://jsfiddle.net/pUeue/

The function is being defined inside a load handler and thus is in a different scope. As @ellisbben notes in the comments, you can fix this by explicitly defining it on the window object. Better, yet, change it to apply the handler to the object unobtrusively: http://jsfiddle.net/pUeue/

$('input[type=button]').click( function() {
   alert("test");   
});

请注意,以这种方式应用处理程序,而不是内联处理,可以保持HTML清洁。我使用的是jQuery,但如果你喜欢,你可以在有或没有框架的情况下使用它,或者使用不同的框架。

Note applying the handler this way, instead of inline, keeps your HTML clean. I'm using jQuery, but you could do it with or without a framework or using a different framework, if you like.

这篇关于为什么我的JavaScript不能在JSFiddle中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆