在 jsfiddle 中测试一个函数 [英] testing a function in jsfiddle

查看:18
本文介绍了在 jsfiddle 中测试一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,这里的问题很愚蠢.如果您发布有关 javascript 或 jquery 的问题,人们通常会说 - 创建一个 jsfiddle.

所以,我做到了.我的问题是关于使用 jquery 使 div 向上滑动,但是,我什至无法获得在 jsfiddle 中运行的基本 javascript 函数.

http://jsfiddle.net/ubq6E/

你好

函数 showit(){警报('你好');}

一个div,点击它调用一个javascript函数,但是jsfiddle说这个函数没有定义.你不能在 jsfiddle 中做到这一点吗?

解决方案

您在 jsfiddle 中选择了默认的 onLoad 选项.

这会导致网站将您的整个代码包装在一个回调函数中,这意味着您的 showit 函数不是 DOM0 内联事件处理程序所要求的全局函数.

有几种解决方法,按照我个人的喜好顺序:

  1. 不要使用 DOM0 内联处理程序,它们真的老派 - 而是查看 element.addEventListener() 并将您的标记与您的 JS 分开.

  2. 改用 window.showit = function() { ... } 来强制您的函数出现在全局命名空间中.

  3. 选择不换行"选项之一

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?

解决方案

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

这篇关于在 jsfiddle 中测试一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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