QQ726535609 QQ726535609 - 3 months ago 8
HTML Question

Why doesn't this onclick handler on an img work?

I use a

<img>
, set
onclick()
method, but it cannot call the method:

<!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>


Why when I click the
<img>
, it can not execute the
close()
cody?
I really don't know how to resolve the issue.

Answer

When you define a function named close on the global context (window, in case of the browser), you're actually defining it as window.close. But, since window.close is reserved for the purpose of closing the current window, they collide.

Change the name to something less generic:

function closeIt() {
    // ...
};