简体   繁体   中英

Assign the 'onmouseover' event handler

Please tell me what is wrong with this code:

 <script type="text/javascript" >

function createimg()
       {
         var img = new Image();
       img.src='link/to/image';
       img.alt='Next image';  img.id = 'span1'; img.style.zIndex = 10;
       img.style.position = 'absolute';  img.style.display='block'; img.style.top = '130px';
       img.style.padding='10px'; img.style.left='440px';    img.className ='dynamicSpan';
        document.body.appendChild(img);
        return img;
        }

    function al()
    {
     alert('loaded');
    }
   a = createimg();

    a.onmouseover = al();

</script>

In specific the last part, where I'm trying to assign the 'onmouseover' event handler of a, which is an image element. It does not assign this event handler for some reason and just executes the function on page load instead.

What is wrong?

Tony

a.onmouseover = al;

When you write al() you are calling the function on the spot and assigning the return value of the function (which is undefined since there's no return statement) to a.onmouseover . Instead you want to assign the function itself so you just need to remove the parentheses.

Well, for starters, your code is not formatted in a way that makes it easy to read.

But your problem is here:

a.onmouseover = al();

What you really want is:

a.onmouseover = al;

The () operator invokes the function. So the expression al() is equal to the result of executing the function al -- which means the al function must be executed before its result (which, in this case, is undefined ) can be assigned to a.onmouseover .

By contrast, if you just use al , the expression is equal to the function object al , which is what you actually want to assign to the event. In that case, when the event is triggered, the al function is executed.

Try

a.onmouseover = al;

instead of

a.onmouseover = al();
    a.onmouseover = al;

Replace:

a.onmouseover = al();

With:

a.onmouseover = al;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM