gpt4 book ai didi

javascript - 调用鼠标悬停回调时的js语法错误

转载 作者:行者123 更新时间:2023-11-30 08:17:04 25 4
gpt4 key购买 nike

我有一些 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);

关于javascript - 调用鼠标悬停回调时的js语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1401743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com