onclick=function() 未在文本元素上调用

onclick=function() not being called on text element

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>

        <div id="overdiv">

            <style>
            .cross{
                cursor:Default;
            }
            
            </style>
            
            <script>
              function close(){
              alert("why don't you work");
              }
            </script>
            
            <div id="lowerDiv">
              <a class="cross" onclick=close()>x</a>
            </div>
            
            </div>

    </body>
    </html>

我不明白为什么 x 的 onclick 不起作用,即使我用 div...

包围 x

我有什么办法可以解决,或者我应该用什么其他方法来解决这个问题?我想通过按 x 关闭 window,我知道该怎么做,但我就是无法让 onclick 工作...感谢任何帮助。

<a class="cross" onclick=close()>x</a>

此代码的 onclick 函数有问题。你没有指定函数。您需要在“”标签之间制作函数代码。

请像这样更改代码:

<a class="cross" onclick="close()">x</a>

https://whosebug.com/users/479156/ivar

Ivar 让我知道问题是命名函数“close()”, 所以我不得不给它取个不同的名字。

如此处解释:onclick calling hide-div function not working

谢谢伊瓦尔!

我改进了你的代码,它开始工作了

  • 添加 "" 以在您的标签中运行 onclick="onClose()",
  • 你最好在 <header> 中添加 <script> 而不是在 <body>
  • 您不能调用您的函数 close(),因为它是保留名称。例如你也不能命名 var return etc

<!DOCTYPE html>
<html>
<head>
    <script>
        function onClose() {
            console.log("why don't you work - I work");
        }
    </script>
    <style>
      .cross {
        cursor: Default;
      }
    </style>
</head>
<body>
<div id="overdiv">
    <div id="lowerDiv">
        <a class="cross" onclick="onClose()">x</a>
    </div>
</div>
</body>
</html>