How to fix 'Typerror is undefined' message for a function in javascript?

半世苍凉 提交于 2019-12-13 05:37:56

问题


I am trying to manipulate the background image as soon as the user hovers over a selected option. I tested my code in firebug and loaded up the page. Instantly I get:

TypeError: document.getElementsByTagName(...).style is undefined

var bg = document.getElementsByTagName("html").style.backgroundColor = "white";

and for the hover I get:

TypeError: bg.document is undefined

bg.document.getElementsByTagName("html").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')";

How do I fix this error?

HTML CODE:

<form>
    <!--show a large print of green font color and size money-->
    Select your DSLR budget range:
    <select id="budgetSel" onChange="onChange();">
        <option value="selectOneBudget" selected="selected">Select one</option>
        <option value="fiveHundredDollars" onMouseOver="changeBackgroundImage(this);">&lt; $500</option>
        <option value="thousandDollars" onMouseOver="changeBackgroundImage(this);">&lt; $1000</option>
    </select>
</form>

CSS CODE:

html{
background: url('http://upload.wikimedia.org/wikipedia/commons/8/8a/1000_USD_note%3B_series_of_1934%3B_obverse.jpg') no-repeat center center fixed;
/*-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;*/
background-size: cover;
min-width:1300px; /*keep the same width when resizing*/
}

JAVASCRIPT:

var bg = document.getElementsByTagName("html").style.backgroundColor = "white";
// function to dynamically change the background image when user hovers over an option in select menu
function changeBackgroundImage(bg)
{
   bg.document.getElementsByTagName("html").style.backgroundImage = "url('http://upload.wikimedia.org/wikipedia/commons/b/be/500_USD_note%3B_series_of_1934%3B_obverse.jpg')";
}

回答1:


as its name implies:

document.getElementsByTagName

returns a collection of tags not a single node, I said a collection because it doesn't actually return an array but it returns an array-like object.

If you only need to get the html node, you can simply do:

document.lastChild.style.backgroundColor = "white";

and also

document.documentElement.style.backgroundColor = "white";

but if you need to find it using a finder function like that, you should do this instead:

document.getElementsByTagName("html")[0].style.backgroundColor = "white";

and also this one:

document.querySelector("html").style.backgroundColor = "white";



回答2:


getElementsByTagName() returns array of match elements, so you should use index 0 in your case.

Should be

document.getElementsByTagName("html")[0].style

instead of

document.getElementsByTagName("html").style


来源:https://stackoverflow.com/questions/22118923/how-to-fix-typerror-is-undefined-message-for-a-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!