我正在为 cms 编写一个插件,该插件在 html 文档末尾嵌入了 jQuery。
我确实在模板代码中动态定义了一些变量,如下所示:
<script>
var name = '<?php echo $nameTakenFromTheDatabase; ?>';
</script>
此代码是我的插件的一部分,它未嵌入在每个页面上。因此,name 并未在每个页面上定义。
我还在一个单独的文件中包含此 Javascript 代码(由 cms 自动添加到页面末尾):
var MyNamespace = (function() {
MyClass = function(name) {
// Do something with name
}
return {
MyClass: MyClass
}
})();
如果 jQuery 嵌入在顶部,我会在我的模板代码中执行类似的操作:
<script>
var name = '<?php echo $nameTakenFromTheDatabase; ?>';
$(document).ready(function() {
new MyNamespace.MyClass(name);
});
</script>
但是,由于 jQuery 包含在底部,我无法做到这一点($ 尚未定义)。我也不能只将 jQuery-DomReady 调用添加到单独的代码文件中,因为这会在每个页面上执行,但 name var 不会在每个页面上初始化并破坏代码。
我能做什么?旧的 document.ready 是一个明智的方法吗?
最佳答案
您可以在脚本中定义方法,并从全局 javascript 文件执行它们。
如果您在页面中执行类似的操作
<script>
var name = '<?php echo $nameTakenFromTheDatabase; ?>';
function runWhenReady(){
new MyNamespace.MyClass(name);
}
</script>
然后在页面底部添加的全局文件中,您可以执行以下操作:
$('document').ready(function() {
if (typeof runWhenReady != 'undefined') {
runWhenReady();
}
});
如果您有创意,您可以将“runWhenReady”制作为方法集合,该集合将始终在页面准备好时加载。
编辑我添加了一个使用数组的示例:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
// check if array is already created. This is necessary if it is possible to render multiple pages which uses the runWhenReadyFunctions collection.
if (typeof runWhenReadyFunctions == 'undefined'){
window.runWhenReadyFunctions = new Array();
}
runWhenReadyFunctions.push(function(){
$('#testDiv').text('hello world!');
});
runWhenReadyFunctions.push(function(){
$('#testDiv2').text('hello another world!');
})
</script>
<div id="testDiv"></div>
<div id="testDiv2"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
if (typeof runWhenReadyFunctions != 'undefined') {
$.each(runWhenReadyFunctions, function(idx, func){
func();
});
}
</script>
</body>
</html>
关于javascript - jQuery插入页脚时如何定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10352057/