我在某种程度上是关于以下结构的初学者问题:
<body>
<p id="text_object">Some text</p>
<button id="button_change_text">change text on click</button>
// Individual script on page template
// ----------------------------------
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
// Footer from included footer.php with universal main.js file
// ------------------------------------------------------------
<footer>
<script type="text/javascript" src="main.js">
</footer>
</body>
我的 main.js 包含以下内容:
// declaration of function for writing new text into text object on load
function changeTextOnLoad(object) {
object.text('New text');
}
// declaration of click function
$('#button_change_text').on('click', function() {
$('#text_object').text('New text');
});
我的问题:我的控制台告诉我,changeTextOnLoad()未定义。但是点击按钮并通过这种方式更改文本非常合适。原因在哪里? 为什么在我的main.js文件中,click函数被触发而不是changeTextOnLoad函数?
答案 0 :(得分:1)
在main.js文件加载之前,您正在调用changeTextOnLoad函数。将函数调用放在onload事件回调中或将include放在调用上面
window.onload = function(){
var object = $('#text_object');
changeTextOnLoad(object);
};
//Or using addEventListener
window.addEventListener("load",function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or since you are using jQuery
$(document).ready(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
//Or
$(function(){
var object = $('#text_object');
changeTextOnLoad(object);
});
OR
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
var object = $('#text_object');
changeTextOnLoad(object);
</script>
答案 1 :(得分:0)
因为main.js是另一个文件,浏览器需要时间来下载它。但是在此之前你运行changeTextOnLoad(object);
。