开发者

JavaScript - "this" as function argument

开发者 https://www.devze.com 2023-01-14 02:29 出处:网络
When my document loads, I\'d like to have JavaScript reload my images\' sources. To do so, I got the following code in my HTML document:

When my document loads, I'd like to have JavaScript reload my images' sources. To do so, I got the following code in my HTML document:

<img src="#" id="mypic" onloa开发者_C百科d="reloadImage(this);"/>

and in my JavaScript document:

function reloadImage(imageElement) {
    imageElement.src = "http://www.somedomain.com/image.png";
}

However, this doesn't work. Am I using this incorrectly, or does the problem lie elsewhere?


The syntax you use is correct in principle. The problem is that for the URL #, being an invalid image URL, the load event is probably never fired.


You're using this correctly, however that looks like something that might result in your function being called repeatedly if the image loads, however I doubt an image loaded from # is going to ever load. Are you sure that's what you want?

(Why are you calling your code a "document"?)


The code SHOULD work, however since you do not have an image in the tag, the onload has nothing to trigger on

Try this

<img src="blank.gif" id="mypic" onload="reloadImage(this);"/>

and test

if (imageElement.src.indexOf('blank')!=-1) imageElement.src="http://www.somedomain.com/image.png";
0

精彩评论

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