簡體   English   中英

javascript不會在for之后執行代碼

[英]javascript doesnt execute code after for

我在javascript中創建了2個函數,這些函數會在click事件上觸發,問題是for循環后,警報沒有執行。

 function myfunc() { for (var i = 0; i < 4; i++) { document.getElementsByTagName("h1")[i].style.color="red"; } alert("alert 1"); //this should be executed after the for since it is part of the function code. } function myfunc2() { for (var j = 0; j < 4; j++) { document.getElementsByTagName("h1")[j].style.color="navy"; } alert("alert 2"); //this should be executed after the for since it is part of the function code } 
 <h1 onClick="myfunc()">primo h1</h1> <h1 onClick="myfunc2();">secondo h1</h1> 

應用新的樣式屬性之前,您需要檢查DOM中有多少個h1標簽。 您實際上是在嘗試對undefined進行更改。

 var elements = document.getElementsByTagName("h1"); function myfunc() { for (var i = 0; i < elements.length; i++) { elements[i].style.color="red"; } alert("alert 1"); //this should be executed after the for since it is part of the function code. } function myfunc2() { for (var j = 0; j < elements.length; j++) { elements[j].style.color="navy"; } alert("alert 2"); //this should be executed after the for since it is part of the function code } 
 <h1 onClick="myfunc()">primo h1</h1> <h1 onClick="myfunc2();">secondo h1</h1> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM