TypeError:node.setAttribute不是函数

Sin*_*hil 4 html javascript error-handling try-catch setattribute

我收到一个错误:当我尝试在我的网页上调用以下函数时,"TypeError:item.setAttribute不是函数":

function list() {
    var colors = document.getElementById('colors');
    var colors = colors.childNodes.length;
    for (var i = 1; i < broj; i++) {
        var item = colors.childNodes.item(i);
        item.setAttribute("id", i);
        item.setAttribute("onmouseover", "moveover(src)");
        item.setAttribute("alt", "Color");
        item.hspace = "2";
        item.height = "23";
    }
}

function moveover(colorAddress) {
    var source = colorAddress;
    var image = source.slice(0, source.length - 4);
    var start = "url(";
    var extension = ".jpg)";
    var newImage = start.concat(image, extension);
    document.getElementById('image').style.backgroundImage = newImage;
}

window.onload = function() {
    try {
        list();
    } catch (err) {
        alert(err);
    }
}
Run Code Online (Sandbox Code Playgroud)

mouseover()函数是函数的辅助函数,该list()函数应在将事件onmouseover属性添加到list()函数中的元素时触发.

当我加载页面时,会弹出警告框并给出上述错误.

它实际上是将所有属性添加到我的元素中,但我不明白为什么会出现此错误.因为这个错误触发它会阻止我在加载之后立即运行另一个函数.

为什么会出现此错误?

这是我试图操作的HTML文档:

<div id="image" style="background-image: url(images/nova_brilliant/1.jpg)"></div>
<div id="tekst">
     <h1>Nova Brilliant</h1>

    <div id="contents">
        <p>Hover with your mouse over the desired color to see the kitchen in that color:</p>
        <div id="colors">
            <img src="images/nova_brilliant/1.gif">
            <img src="images/nova_brilliant/2.gif">
            <img src="images/nova_brilliant/3.gif">
        </div>
        <p>Other available colors:</p>
        <div id="others">
            <img src="images/nova_brilliant/4.gif">
            <img src="images/nova_brilliant/5.gif">
            <img src="images/nova_brilliant/6.gif">
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

当用户将鼠标悬停在div中的3个图像中的一个上时,div中id="colors"的背景图像id="image"应该更改并且它确实会发生变化,这只是我得到了令人烦恼的错误,这使我无法再运行另一个脚本这一个加载.

Tim*_*own 7

机会是您调用setAttribute()的节点是文本节点而不是元素.最简单的解决方案是nodeType在调用之前检查属性setAttribute():

var item = colors.childNodes[i];
if (item.nodeType == 1) {
    // Do element stuff here
}
Run Code Online (Sandbox Code Playgroud)

抛开:设置事件处理程序属性(例如onmouseovervia setAttribute())通常是一个坏主意,因为它不能像旧IE中指定的那样工作(以及后面的IE中的兼容模式).改为使用等效属性:

item.onmouseover = function() {
    moveover(this.src);
};
Run Code Online (Sandbox Code Playgroud)