為什么放到<head>里面就不執(zhí)行
<script type="text/javascript">
var main = document.body;
//創(chuàng)建鏈接
function createa(url,text)
{
? ? var link=document.createElement('a');
? ? link.setAttribute('href',url);
? ? link.innerHTML=text;
? ? link.style.color='red';
? ? main.appendChild(link);
}
// 調(diào)用函數(shù)創(chuàng)建鏈接
createa('http://idcbgp.cn','慕課網(wǎng)');
</script> ?
這段代碼放到body里面沒問題,放到head里面就失效了,為什么會這樣
2019-04-18
放在<head>里的代碼一般是預加載,只執(zhí)行一次,并且瀏覽器是按照先后順序編譯的,要把代碼再次加載,要加把代碼都放到window.onload=function(){? }的大括號里,代碼如下:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>
<script type="text/javascript">
window.onload=function(){
var main = document.body;
//創(chuàng)建鏈接
function createa(url,text)
{
? ? var link=document.createElement('a');
? ? link.setAttribute('href',url);
? ? link.innerHTML=text;
? ? link.style.color='red';
? ? main.appendChild(link);
}
// 調(diào)用函數(shù)創(chuàng)建鏈接
createa('http://idcbgp.cn','慕課網(wǎng)');
}
</script>??
</head>
2019-01-29
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>
</head>
<body>
<script type="text/javascript">
var main = document.body;
//創(chuàng)建鏈接
function createa(url,text)
{
? ? var a=document.createElement("a");?
? ? a.href=url;
? ? a.innerHTML="慕課網(wǎng)";
? ? main.appendChild(a);
? ??
}
// 調(diào)用函數(shù)創(chuàng)建鏈接
createa("http://idcbgp.cn","慕課網(wǎng)");
</script>?
</body>
</html>
2019-01-19
createa('http://idcbgp.cn','慕課網(wǎng)');
是調(diào)用函數(shù)的文本。文本應該在body里。head的文本不顯示。