我有一些javascript代码可以创建带有鼠标悬停回调的img标记,并将img标记添加到页面中。问题是每当调用回调时都会发生javascript语法错误(在Firefox控制台中)。

这段代码演示了这个问题......

    
        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);
    

当回调函数为空函数时,甚至会发生语法错误。

任何人都可以解释是什么导致语法错误以及如何解决它?

(我在Win XP上使用FF 3.5.2。)

有帮助吗?

解决方案

您正在传递一个需要字符串的函数。试试这个:

    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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top