[英]call function from external js (php) file
I have a file where I keep all scripts so my pages wouldn't get messy (I have php file which generates required javascript). 我有一个保存所有脚本的文件,因此我的页面不会混乱(我有生成所需JavaScript的php文件)。 My includes basically look like this:
我的包括基本上是这样的:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.php"></script>
</head>
<body>
<input type="button" onClick="return blah();" />
</body>
</html>
script.php script.php
<?php
header("content-type: application/x-javascript");
?>
function blah()
{
alert("blah");
}
$(document).ready(function()
{});
In script.php there's jquery wrapper $(document).ready where I keep all jquery related stuff. 在script.php中,有一个jquery包装器$(document).ready,其中保留了所有与jquery相关的东西。 The funny thing is, when I put function blah() inside this wrapper I get "blah is not defined" error, but when I put it outside - works perfectly.
有趣的是,当我将函数blah()放入此包装器中时,出现“ blah is not defined”错误,但是当我将其放置在外部时,它可以正常工作。 So, what could be the problem?
那么,可能是什么问题呢?
Surely that's a simple scoping issue? 当然,这是一个简单的范围界定问题?
$(function(){
window.blah = function() {
};
});
If you do this: 如果您这样做:
function(){
var foo = function(){
}
// Other stuff
}
... you are defining a private function that only exists inside the external function. ...您正在定义仅在外部函数内部存在的私有函数。 If you want it global, you must either define it outside:
如果要全局使用它,则必须在外部定义它:
var foo = function(){
}
jQuery.ready(
function(){
// Other stuff
}
);
... or append it to a global object, such as window: ...或将其附加到全局对象,例如window:
jQuery.ready(
function(){
window.foo = function(){
}
// Other stuff
}
);
It's worth noting that using external files does not change this. 值得注意的是,使用外部文件不会改变这一点。
blah() is not defined. 等等() 没有被定义。 Your function is called checkField().
您的函数称为checkField()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.