简体   繁体   中英

How to pass an event of a button click to a callback function

Fiddle: http://jsfiddle.net/cmw0s2rk/

function HandleTopNavClick($elem, pretext = "", replace = false, e) {
  debugger;
  e.preventDefault();
  var href = $elem.href;
}

$("ul.check-it li a").on("click", HandleTopNavClick($(this), "clickhere_", true, event));

Any idea why the event is not carrying over to the function?

You are synchronously calling handleTopNavClick, then passing its result into .on. Instead, you want to create a function and pass that into .on, which will later be called back with the event.

$("ul.check-it li a").on("click", function(event) {
  HandleTopNavClick($(this), "clickhere_", true, event)
});

You probably meant to use HandleTopNavClick as the callback function, but instead, you are using the return value of the function as the callback function, which is undefined.

You can just use HandleTopNavClick as the callback function for the click event handler and use this to refer to the element.

function HandleTopNavClick(e) {
  debugger;
  e.preventDefault();
  var href = $(this).attr('href');
}

$("ul.check-it li a").on("click", HandleTopNavClick);

JSFiddle Demo: http://jsfiddle.net/cmw0s2rk/8/

与尼古拉斯类似,这可以通过箭头功能实现,有时可以读得更好。

$("ul.check-it li a").on("click", event => HandleTopNavClick($(this), "clickhere_", true, event));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM