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

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

问题描述

我不知道这个 JSFiddle 有什么问题.

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

HTML:

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

JavaScript:

JavaScript:

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

当我点击按钮时 - 什么也没发生.控制台显示未定义测试"

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

我已经阅读了 JSFiddle 文档 - 那里说 JS 代码被添加到 并且 HTML 代码被添加到 (所以这个 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 在评论中指出的那样,您可以通过在 window 对象上显式定义它来解决此问题.更好的是,更改它以不显眼地将处理程序应用于对象: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天全站免登陆