為什么這樣行?而這樣卻不行?
<script type="text/javascript">
var main = document.body;
function createa(url,text)
{
?var a=document.createElement("a")
?a.setAttribute("href",url)
?a.setAttribute("style","color:red")
?var b=document.createTextNode(text)
?a.appendChild(b)
?main.appendChild(a)
}
// 調(diào)用函數(shù)創(chuàng)建鏈接
this.createa("http://idcbgp.cn","慕課網(wǎng)")
</script>?
以上代碼可以正確運(yùn)行,而下面的代碼卻不能正確運(yùn)行是為什么?
<script type="text/javascript">
var main = document.body;
//創(chuàng)建鏈接
function createa(url,text)
{
?var a=document.createElement("a")
? ? ? a=a.setAttribute("href",url)
? ? ?a=a.setAttribute("style","color:red")? ?//就這里與上面的代碼不一樣,這里用了賦值的方式但是這段代碼就是報錯所‘setAttribute’
?var b=document.createTextNode(text)//沒定義
?a.appendChild(b)
?main.appendChild(a)
}
// 調(diào)用函數(shù)創(chuàng)建鏈接
this.createa("http://idcbgp.cn","慕課網(wǎng)")
</script>?
2020-04-22
setAttribute方法沒有返回值,不能賦值給變量
2020-03-23
注意一下:
?a=a.setAttribute("href",url)
? ? ?a=a.setAttribute("style","color:red")? ?//就這里與上面的代碼不一樣,這里用了賦值的方式但是這段代碼就是報錯所‘setAttribute’
a=? 去掉后運(yùn)行就可以了,敲碼時多注意一下,這些很基礎(chǔ)的。
a.setAttribute("href",url)
a.setAttribute("style","color:red")? ?//就這里與上面的代碼不一樣,這里用了賦值的方式但是這段代碼就是報錯所‘setAttribute’
2020-03-06
我的答案如圖所示: