情况为"document.ready"阻碍 [英] Case, when "document.ready" obstruct

查看:76
本文介绍了情况为"document.ready"阻碍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有php文件,在这个文件中我有以下代码:

I have php file, in this file I have this code:

    <script language="JavaScript" type="text/javascript" src="jquery.js"></script>
    <script language="JavaScript">
        $(document).ready( function () {
            var myvar = <?php   echo json_encode($myvar);   ?> ;
        });
    </script>
    <script language="JavaScript" type="text/javascript" src="costum.js">  </script>

在costum.js文件中,我有代码:

and in costum.js file I have code:

$(document).ready( function () {
    alert(myvar );
});

这不起作用,错误控制台返回"myvar is undefined"

this not working, error consol returns "myvar is undefined"

如果在php文件中我写了这个(即没有"document.ready")

if in php file I write this (that is, without "document.ready")

 <script language="JavaScript">
     var myvar = <?php   echo json_encode($myvar);   ?> ;
 </script>

在costum.js文件中,代码已正常运行.请告诉为什么会这样?

in costum.js file, code alredy is working. Please tell why this happened?

推荐答案

尝试使用

<script>
    var myvar;
    $(document).ready( function () {
        myvar = <?php   echo json_encode($myvar);   ?> ;
    });
</script>

必须将您的变量声明为全局变量(换句话说,在外部作用域中),以便从这两个document.ready函数进行查看.

your variable has to be declared as global (or in other words, in the outer scope) to be viewed from both document.ready functions.

作为旁注,不需要language属性.甚至type也是没有必要的(如果您使用的是html5 doctype)

As a side note language attribute is not necessary. Even type is not necessary (if you're using html5 doctype)

这篇关于情况为"document.ready"阻碍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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