代码在jsfiddle中有效,但在html文档中无效 [英] code works in jsfiddle but not in html document

查看:85
本文介绍了代码在jsfiddle中有效,但在html文档中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用javascript的初学者,希望有人可以帮助我解决此问题.我正在尝试使ID为"move"的div来回滑动.该代码可在jsfiddle中使用,但是当我将其放入html文档时将无法使用.我尝试将顶部放置在单独的js文件中,并仅使用代码的最后一行在头部调用变量:

I am a beginner with javascript and am hoping that someone can help me solve this issue. I am trying to make a div with the id, "move," slide back and forth. The code works in jsfiddle, but will not work when I place it into my html document. I have tried placing the top portion in a separate js file and calling the variable in the head only using the last line of the code:

animateMe($('#move'), 2000);

那没有用.然后,我尝试将整个js脚本放到头部,这也没有用.这是我的html文档开头的代码:

That did not work. I then tried placing the entire js script into the head and that also did not work. This is the code in the head of my html document:

<script type="text/javascript" src="javascript/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
 $(targetElement).css({ left: '50px', top: '50px' }).animate({
        'left': '200px'  },{
       duration: speed,
        complete: function () {
            $(this).animate({
            'left':'50px'
            },{
            duration: speed,
            complete: function () {
         animateMe(this, speed);
                }
            })
        }
        }
   ); 
  };
animateMe($('#move'), 2000);</script>

这是正文中的代码.我通常使用外部CSS文档,但是为了使内容简短些,我在这里使用了内联CSS.

This is the code in the body. I normally use an external css document, but for the sake of trying to keep things shorter, I used inline css here.

<div id="move" style="position: absolute; width: 100px; height: 100px; background-color: green;"></div>

我将从jsfiddle中获取代码,但是将其放置在头部或单独的js文件中.不知道这样做是否会导致脚本无法正常工作.任何帮助表示赞赏.谢谢大家.

I am taking the code as is from jsfiddle and placing it into the head or into my separate js file though. Not sure if doing this is what is causing the script to not work. Any help is appreciated. Thank you all in advance.

这是我在jsfiddle上工作的链接: http://jsfiddle.net/wrdweaver6/r8Kf9/

This is the link to my work on jsfiddle: http://jsfiddle.net/wrdweaver6/r8Kf9/

推荐答案

您想将代码放入其中一个

You want to put your code inside either

$(document).ready(function() {
    // Your code here
});

window.onload = function() {
    // Your code here
};

在执行javascript之前,首先需要加载所有元素.使用jsFiddle,您不必执行此操作,但这可能是导致它无法在jsFiddle之外工作的原因.

All of the elements need to be loaded first before the javascript executes. With jsFiddle you don't have to do this, but this is probably what's causing it not to work outside of jsFiddle.

这篇关于代码在jsfiddle中有效,但在html文档中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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