gpt4 book ai didi

javascript - 为什么 img 上的这个 onclick 处理程序不起作用?

转载 作者:行者123 更新时间:2023-11-30 09:44:46 25 4
gpt4 key购买 nike

我使用 <img> , 设置 onclick()方法,但它不能调用该方法:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date</title>
</head>
<body>
<div style="width: 300px; height: 200px;" id="img-div" >
<img id="img-id" src="resources/01.jpg" width="200px" height="80px" style="CURSOR:pointer;" onclick="close();">
</div>
<script type="text/javascript">
function close(){

console.log('js');

alert(111);
}

</script>
</body>
<html>

为什么当我点击 <img> , 它不能执行 close()科迪?我真的不知道如何解决这个问题。

最佳答案

正如 haim770 在评论 (编辑;现在是 an answer ) 中指出的那样,问题在于函数的名称。全局命名空间真的很拥挤,其中已经有一个您无法覆盖的 close 函数。使用不同的名称。

这是使用onxyz 属性样式事件处理程序的众多原因之一:它们要求您的函数是全局函数。相反,使用不需要您使用全局变量的现代事件处理:

document.getElementById("img-id").addEventListener("click", function() {
// ...your code here...
}, false);

确保上面的代码在 img 元素存在后 运行。 (如果您必须支持 IE8 或 IE9-11 等过时的浏览器,当它们因 [in] 兼容模式而陷入困境时 - see this answer。)

例子:

document.getElementById("img-id").addEventListener("click", function() {
// ...your code here...
alert("Clicked");
}, false);
<div style="width: 300px; height: 200px;" id="img-div">
<img id="img-id" src="https://www.gravatar.com/avatar/4f8efc215ecc23017b42334c9b30c49b?s=32&d=identicon&r=PG&f=1" style="CURSOR:pointer;">
</div>

关于javascript - 为什么 img 上的这个 onclick 处理程序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39326678/

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