我的JavaScript代码无法在本地运行,但可以在jsfiddle上正常工作,为什么? [英] My JavaScript code is not working locally, but works fine on jsfiddle, why?

查看:68
本文介绍了我的JavaScript代码无法在本地运行,但可以在jsfiddle上正常工作,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一些javascript代码,用于将表单提交到代码中.这是代码:

I created some javascript code that submits the form out the tag. Here is the code:

<script type="text/javascript">
var myForm = document.forms['myForm'];

var formSubmit = document.getElementById('formSubmit');


formSubmit.onclick = function(){
myForm.submit();
}
</script>

<form name="myForm" action="http://msn.com" method="post"> 
</form>
<div id="formSubmit"><button>Click me</button></div>

当我在 http://jsfiddle.net/HrCxz/上尝试此代码时,它工作正常.但是,当我将此代码添加到HTML文件中并运行页面时,它不起作用.代码有什么问题?请解决此问题,并在此先感谢.

When i try this code on http://jsfiddle.net/HrCxz/ it works fine. But When I add this code in an HTML file and run the page, It doesn't work. What's wrong with the code? Please fix this, and many thanks in advance.

推荐答案

在小提琴中,您的代码在onload处理程序中运行.这是默认选项,但是左侧面板允许您对其进行更改.如果将其更改为在<head>中运行,则小提琴也不起作用: http://jsfiddle. net/HrCxz/1/

In the fiddle your code is run inside an onload handler. This is the default option, but the left-hand panel allows you to change it. If you change it to run in the <head> then the fiddle doesn't work either: http://jsfiddle.net/HrCxz/1/

您需要添加自己的onload处理程序,或者将脚本块移动到它尝试操纵的元素之后.脚本块按照浏览器从上到下解析页面时发现的顺序执行.任何给定脚本块中的JS都只能操作已解析的元素,即看起来更接近源开头的元素,除非您将代码放入从onload事件(或从文档就绪)调用的事件处理程序中适用于支持它的浏览器,或者如果您使用提供它的库或自己编写代码.

You need to either add an onload handler of your own, or move your script block to after the elements it tries to manipulate. Script blocks are executed in the order they're found as the browser parses the page top to bottom. JS in any given script block can only manipulate elements that have already been parsed, i.e., ones that appear closer to the beginning of the source, unless you put your code in an event handler called from the onload event (or from document ready for browsers that support it or if you use a library that provides it or otherwise code it yourself).

这篇关于我的JavaScript代码无法在本地运行,但可以在jsfiddle上正常工作,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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