开发者

Swapping images using javascript

I just started reading about JavaScript. As a language, I don't have any trouble with it, but I came across an annoying situation.

I was going to try my first JavaScript function for a simple action: changing the src attribute of an <img>.

So let's imagine I have this code in index.html:

function activate(id) {
  document.images(id).src = "home-on.jpg";
}

function deactivate(id) {
  document.images(id).src = "home-off.jpg";
}
<img id="home" src="home-off.jpg" onmouseover="activate('home')" onmouseout="deactivate('home')"开发者_运维技巧/>

The code works perfectly on Google Chrome (swapping the image when the mouse is over, and out), but I have no luck with Firefox.

Any help?


You're using the wrong syntax to get the images.

You need to write document.images[id] (With brackets [], not parentheses ())

The document.images collection is an associative array, which is indexed using brackets.
Parentheses are used to invoke a function; I don't know why your code worked in Chrome.


SLaks has entered the correct answer for this particular question.

However, you will find in JavaScript that there is a lot of cases like this where incorrect syntax will work in one browser but not in the next. For ensuring that you maintain cross browser compatibility in JavaScript you might find a library such as jQuery very handy. Not only does it attempt to ensure that your JavaScript code is compatible with all browsers, it also extends a lot of great functionality.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜