Mik*_*e W 1 javascript callback syntax-error
我有一些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);
Run Code Online (Sandbox Code Playgroud)