简体   繁体   中英

js syntax error when invoking mouseover callback

I have some javascript code that creates an img tag with a mouseover callback, and adds the img tag to the page. The problem is that a javascript syntax error happens (in the Firefox Console) whenever the callback is invoked.

This code demonstrates the problem...

var imgUrl = 'http://sstatic.net/so/img/logo.png';
        var img = document.createElement('img');
        img.setAttribute('src', imgUrl);
        img.setAttribute('onmouseover', function() {
            alert('mouseover ' + imgUrl);
        });
        document.body.appendChild(img);

The syntax error even happens when the callback function is an empty function.

Can anyone explain what's causing the syntax error and how to fix it?

(I'm using FF 3.5.2 on Win XP.)

You're passing in a function where a string is expected. Try this instead:

    var imgUrl = 'http://sstatic.net/so/img/logo.png';
    var img = document.createElement('img');
    img.src = imgUrl;
    img.onmouseover = function() {
        alert('mouseover ' + imgUrl);
    };
    document.body.appendChild(img);

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