问题
I have a jQuery onClick
handler, writed with an anonymous function like that:
$("#selector").on("click" function(){
// do something
})
I would generalize the anonymous function extracting the logic in a named function, that drive me to something like:
$("#selector").on("click" namedFunction())
function namedFunction(){
// do something
}
To me seemed a good solution. But there's a drawback since the namedFunction
is executed as soon script is loaded. Here you can test the bad behaviour.
回答1:
Just pass the reference
of that function itself.
Try,
$("#selector").on("click", namedFunction);
回答2:
You don't need the ()
for your function here:
$("#selector").on("click", namedFunction)
回答3:
try like
function namedFunction(){
alert("Hello world!")
}
$("#clickTester").on('click', namedFunction)
Updated Fiddle
回答4:
Named function[view jsFiddle]
Function namedFunction () {
alert("Hello world!");
}
$("#clickTester").on('click', namedFunction);
Anonymous function [view jsFiddle]
$("#clickTester").click(function(){
alert("Hello world!");
});
回答5:
Or a shorter version
$("#selector").click(namedFunction);
来源:https://stackoverflow.com/questions/22220216/jquery-on-click-event-that-call-a-named-function