[英]Adding js inside <head> tag is not working
這是工作代碼,我從其他地方找到的。
<html lang="en">
<head>
<meta charset="utf=8">
<style type="text/css">
#posts {
width: 90%;
height: 700px;
margin: auto
}
.post {
width: 100px;
height: 100px;
float: left;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div id="posts">
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
</div>
<script type="text/javascript">
$(".post").each(function() {
var color = '#'; // hexadecimal starting symbol
var letters = ['eee','ddd','ccc','aaa','888','777','666','555']; //Set your colors here
color += letters[Math.floor(Math.random() * letters.length)];
$(this).css("background-color", color);
});
</script>
</body>
</html>
但是,如果我將 js 腳本放在<head>
標記下方,則 js 似乎無法正常工作。 js 腳本只有在我們將它放在<body>
標記內時才起作用的任何原因?
<html lang="en">
<head>
<meta charset="utf=8">
<style type="text/css">
#posts {
width: 90%;
height: 700px;
margin: auto
}
.post {
width: 100px;
height: 100px;
float: left;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript">
$(".post").each(function() {
var color = '#'; // hexadecimal starting symbol
var letters = ['eee','ddd','ccc','aaa','888','777','666','555']; //Set your colors here
color += letters[Math.floor(Math.random() * letters.length)];
$(this).css("background-color", color);
});
</script>
</head>
<body>
<div id="posts">
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
</div>
</body>
</html>
當瀏覽器執行你的第二個腳本時,還沒有元素添加到文檔中。 所以你必須用 window.onload 包裝你的第二個腳本代碼
<script type="text/javascript">
window.onload = () => {
$(".post").each(function() {
var color = '#'; // hexadecimal starting symbol
var letters = ['eee','ddd','ccc','aaa','888','777','666','555']; //Set your colors here
color += letters[Math.floor(Math.random() * letters.length)];
$(this).css("background-color", color);
});
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.