点击按钮事件似乎并不火

问题描述 投票:-1回答:4

我不是新的HTML或JavaScript,虽然我不经常使用它们。我是,但是,很新的PHP,和我目前正面临着试图在我的HTML一个按钮,在PHP中嵌入获得click事件时,一个奇怪的问题:

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="function() { alert('Moo!'); }">Some button</button>
</body>

</html>

没有任何反应,当我点击按钮。是的,当然是在原来多个标记,但它不是有关我的问题。在W3C验证服务说没有任何错误,当我从body标签的底部,它工作正常,以及脚本警报哞。它看起来像click事件不火...任何想法,为什么?

javascript php html
4个回答
3
投票

问题是你的匿名函数的语法。您使用的是函数定义,但你不能马上调用它,或给它一个名称,这样浏览器就没有什么可以用它做。

点击时,你可以尝试改写这样的按钮部分,如果你想立刻调用:

<button type="button" onclick="(function() { alert('Moo!'); })();">Some button</button>

但我的个人喜好将其写入命名函数,并调用它的处理器来代替。


3
投票

这是因为你定义一个函数,不执行它。不要在功能包裹。

onclick="alert('Moo!');"

如果你把它包装在一个函数。你需要执行它。

onclick="(function() { alert('Moo!'); })()"

1
投票

你不能有内联事件处理匿名函数 - 使用alert("Moo")

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="alert('Moo!')">Some button</button>
</body>

</html>

你也可以使用一个命名函数:

function moo() {
  alert("Moo!");
}
  
<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="moo()">Some button</button>
</body>

</html>

甚至还有一个IIFE:

<!DOCTYPE html>
<html lang="de">

<head>
  <title>Blah</title>
  <meta charset="utf-8">
</head>

<body>
  <button type="button" onclick="(function() { alert('Moo!'); })()">Some button</button>
</body>

</html>

1
投票

您可以通过三种方式结合在onclick属性操作:

  1. <button type="button" onclick="alert('Moo!');">Some button</button>
  2. 使JS代码的功能。 <button type="button" onclick="someFunc()">Some button</button>
  3. 使用closures<button type="button" onclick="(function() { alert('Moo!'); })()">Some button</button>

`

© www.soinside.com 2019 - 2024. All rights reserved.