[英]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.