jquery on click event that call a named function

时光总嘲笑我的痴心妄想 提交于 2019-12-18 13:36:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!