![](/img/trans.png)
[英]How to call function from external js file onload or onclick event into my html
[英]How to use a onload event in html, to call a function in a js file
我有一個html文件,需要從服務器加載一些項目,為此我在js文件中使用了一個函數。 現在,我可以在js文件中使用該函數,而不是在html文件的標記中包含該代碼,然后通過HTML中任何標記的onload屬性(在頁面加載后)調用該函數嗎?
我的HTML頁面是:
<script>
$.getScript(path + "js/jsfile.js");
</script>
<link rel="stylesheet" href="jqueryMobile/jquery.mobile-1.4.5.min.css">
<script src="jqueryMobile/jquery-1.11.2.min.js"></script>
<script src="jqueryMobile/jquery.mobile-1.4.5.min.js"></script>
<header data-role="header">
<a href="#" class="ui-btn ui-icon-back ui-btn-icon-left"
data-role="button" onclick="currentPage.back();">Back</a>
<!--some header tags were here-->
</header>
<div data-role="content" style="padding: 15px" >
<!--some button tags were here-->
</div>
加載此頁面后,我需要執行getColor()函數並將結果提取到html頁面中。
我的jsfile.js頁面是:
currentPage = {};
currentPage.init = function() {
WL.Logger.debug("listofenvironments :: init");
};
currentPage.back = function(){
WL.Logger.debug("Login :: back");
pagesHistory.push(path + "pages/otherpage.html");
$("#pagePort").load(path + "pages/" + "otherpage.html");
};
function getColor(){
//some coding goes on here....
}
我已經嘗試在HTML頁面的標記上使用onload事件,但無法正常工作。 當currentPage.back()函數正常工作時。
在jsfile.js中添加以下行
$(document).ready(function(){
getColor();//ready function will be executed after document elements are loaded.
});
希望這對您有用。
Kindy完成了一些教程。 這些是您無需尋找stackoverflow的基本問題。 但是找到下面的答案
<body onload="myFunc()">
</body>
//in your jsfile
function myFunc() {
//your code
}
如果您希望僅在dom加載后調用該函數並且不需要加載資源,則在加載dom和資源后調用onLoad,請使用jquery ready函數
$(document).ready(function(){
//your code
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.