0

下面是我的页面的 javascript:

    window.onmouseover = function(){
        var body = document.getElementsByTagName("body")
        var h1 = document.getElementsByTagName("h1");
        var a = document.getElementsByTagName("a");
        var p = document.getElementsByTagName("p")
        for(var j = 0; j < p.length; j++) {
            body[j].style.fontFamily = "helvetica";
            body[j].style.backgroundColor = "rgb(250, 250, 240)"
            p[j].style.fontFamily = "courier";
            a[j].onclick = function() {
                this.style.backgroundColor = "Black"
            }
        }
    }

我有一个 h1 元素、一个 a 元素和 10 个 p 元素。出于某种原因,此代码仅更改了第一个 p 元素的字体,尽管其他一切正常?为什么会这样,我该如何解决?

4

2 回答 2

1

如果您只有一个a元素并且(当然)只有一个元素,则body您不能迭代其中的 10 个以上。这会导致循环的第二次迭代出现错误。请改用此代码。

window.onmouseover = function(){
    var body = document.getElementsByTagName("body")
    var h1 = document.getElementsByTagName("h1");
    var a = document.getElementsByTagName("a");
    var p = document.getElementsByTagName("p")

    body[0].style.fontFamily = "helvetica";
    body[0].style.backgroundColor = "rgb(250, 250, 240)"
    a[0].onclick = function() {
        this.style.backgroundColor = "Black"
    }

    for (var j = 0; j < p.length; j++) {
        p[j].style.fontFamily = "courier";
    }
}
于 2012-05-13T02:25:43.093 回答
0

它可能会在第二次循环中产生错误,因为body[1]这将是无效的。移动东西,以便只有操作在p循环内。

于 2012-05-13T02:25:33.763 回答