简体   繁体   English

简单的Javascript函数在jsfiddle中不起作用

[英]Simple Javascript function not working in jsfiddle

I have the following HTML Code. 我有以下HTML代码。

 <select onChange="TestCall()">
<option>Text1</option>
<option>Text2</option>
<option>Text3</option>
<option>Text4</option>
</select>

My JavaScript have a simple alert message like below. 我的JavaScript有一条简单的警告消息,如下所示。

 function TestCall()
{
 alert("Test");
}

Check the following Jsfiddle. 检查以下Jsfiddle。 I have added my script in the javascript area of jsfiddle. 我已将脚本添加到jsfiddle的javascript区域中。 It is not working. 它不起作用。

JSFIDDLE NOT WORKING HERE JSFIDDLE不在这里工作

But If i move script block inside the HTML area of jsfiddle is working. 但是如果我在jsfiddle的HTML区域内移动脚本块,则可以正常工作。 Check the below one. 检查以下一项。

JSFIDDLE WORKING HERE JSFIDDLE在这里工作

What wrong in my code? 我的代码有什么问题? Any Idea? 任何想法?

By default JSFiddle wraps the JS block into onLoad function: 默认情况下,JSFiddle将JS块包装到onLoad函数中:

... leading to something like: ...导致类似:

window.onload = function() {
    function TestCall() {
        alert("Test");
    }
};

This means that your TestCall method is getting out of global scope and is not accessible from HTML attributes. 这意味着您的TestCall方法超出了全局范围,无法从HTML属性访问。

Change the option to No wrap - in <head> or No wrap - in <body> and it will work. 将选项更改为“ No wrap - in <head>或“ No wrap - in <body> ,它将起作用。

DEMO: http://jsfiddle.net/Q9ukX/3/ 演示: http : //jsfiddle.net/Q9ukX/3/

Fiddle 小提琴

It works if you change the settings down the side. 如果您在侧面更改设置,它会起作用。

Change it from onLoad to No Wrap - in body or No Wrap - in head . 将其从onLoad更改为No Wrap - in bodyNo Wrap - in head

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM