您的问题是您提供的onclick
是函数调用而不是函数引用。您的浏览器需要后者。
合适的方式
// Javascript
function foo(e) {
// do stuff, like set the CSS on some elements. Note
// that the 'e' argument is going to be a browser event,
// not the element you're changing.
}
// HTML
<div onclick=foo>
// This passes a reference to a function. Your browser then
// calls foo with an argument of the browser event that was triggered.
错误的方法
// Javascript
function bar(element) {
// do stuff on the *element* argument.
}
// HTML
<div onclick=bar(someDiv)>
// This is wrong because *bar(someDiv)* isn't a reference to
// the function, it's a call to run the function with an argument
// of *someDiv*. onclick isn't expecting this, so the behavior
// you'll get will be not what you expect.
您使用的细节$('.action').css('display', 'block');
是函数调用,而不是引用。您的浏览器正在尝试这样做($('.action').css('display', 'block'))(clickEvent)
,这根本不对。因此,您可以将您的匿名函数包装$('.action').css('display', 'block');
在一个匿名函数中,以使其按照浏览器期望的方式工作:
<div onclick="function(e) {$('.action').css('display', 'block');}">
另请注意$().show(),这可能是一个方便您使用的函数,而不是手动设置 CSS 属性。 还可以考虑为您的 HTML 元素添加一个 ID,然后使用 JQuery 为该 ID 附加一个 onclick 处理程序(即$().click())。