时间:2016-05-21 00:25:48

标签: javascript loops for-loop callback

我在javascript中创建了2个函数,这些函数是在点击事件上触发的,问题是在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>

1 个答案:

答案 0 :(得分:1)

在应用新样式属性之前,您需要检查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>