0

我是 JavaScript 新手,所以请耐心等待...

我有一个链接到我的 HTML 的外部 JavaScript 文档(在 HTML 文档的头部调用)。

在我的 JavaScript 文档中,我对window.onload事件调用了两个函数:

window.onload = function() {
    selected_state();
    viewer();
};

function selected_state() {
    var titleAr = document.getElementsByTagName("title");
    var aAr = document.getElementsByTagName("a");
    // Take the first element of title array. Check if it matches
    // the first element of link array.
    for (i = 0; i <= titleAr.length; i++) {
        for (l = 0; l <= aAr.length; l++) {
            if (titleAr[i].innerHTML === aAr[l].innerHTML) {
                aAr[l].style.color = "#C33";
                break;
            }
        }
    }
};

function viewer() {
    var imgAr = document.getElementsByTagName("img");
    for (var i = 0; i < imgAr.length; i++) {
        imgAr[i].onmouseover = function() {
            this.style.border = "1px solid #CCC";
        }
    }
};​

第一个函数运行没有问题,但第二个函数没有运行。如果我切换它们,那么viewer()首先,然后selected_state()就不会执行。我知道这个问题可能是非常简单的逻辑明智的......任何接受者?

4

2 回答 2

1

Looks like selected_state is breaking when the inner loop finishes in the outer loop's first run; your loop condition is incorrect (must be throwing something like "index out of bounds").

Arrays use a zero-based index:

Change:

for (i=0; i <= titleAr.length; i++) {
    for (l=0; l <= aAr.length; l++) {

To:

for (i=0; i < titleAr.length; i++) {
    for (l=0; l < aAr.length; l++) {
于 2012-06-27T01:14:02.380 回答
0

The only explanation is that both functions throw exceptions after doing whatever it is that makes you think they've run without trouble. Barring their throwing exceptions, first the first one will run, then the second one will run. There's no basic logic error you're missing. But if the first function throws an exception, that transfers control out to the next exception catching frame, which (if you haven't defined one via try...catch) will be outside of your code.

Your best bet is to use a decent debugger to find out what's going on. All major browsers now have decent debuggers built in. In IE and Chrome, press F12 to open the debugger; in other browsers, look at the menus. The debugger will have a "console" where it reports errors. You can also set breakpoints and walk through the code statement-by-statement.


(Edit now you've posted the code.)

Note that your code in selected_state falls prey to The Horror of Implicit Globals. You need to declare i and l with var.

于 2012-06-27T01:11:23.563 回答