情况为"document.ready"阻碍 [英] Case, when "document.ready" obstruct
问题描述
我有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屋!