简体   繁体   中英

jQuery add element to previously defined event handler

With jQuery, is it possible to add elements to a previously defined event handler? I realize the right way to do this would be to define the handler using on() so that dynamically inserted elements will be included, but the issue is the handler I'm trying to extend is defined by code on a server that I don't have access to. The server outputs code like this at the top of the file:

$('#wrapper .block h2').click(function() {
    //do stuff
});

Then, towards the bottom of the page, I've added some custom javascript code that inserts another #wrapper .block h2 element. I'm wondering if there is any way for me to include this new element in the event handler that was defined by the code at the top of the page where the click handler was registered.

Or, is there any way for me to programmatically access the callback function that was defined for that event handler? That way I could recreate it myself using the on() method.

It should be possible for you just to write a new event handler on the same action, it should replace the old one and leave the action to your new one.

Try it out in the console or commandline.

To achieve this you need to access internal event handles stored by jQuery. In previous versions ( prior to 1.8 ) you could do it using Data API, like $('.some').data('events') . However it's no longer available. However you can still access element data object with $._data method. Then you would do something like this:

var events = $._data($(selector)[0], 'events'),
    click = events && events.click;

if (click) $el.on('click', click[0].handler);

However be aware that $._data is a private property, and there is no guarantee that it will not change one day (like previously you could access element data with $.cache , but it's gone now).

Demo: http://jsfiddle.net/dfsq/e94hau62/

The simplest way is, you define the handle in server side, it will be like,

var yourhandler = function() {
    //do stuff
});

Then after you load your new elements, you can hood the "yourhandler" to them, like,

$( document ).ready(function() {
  $('#wrapper .block h2').click(yourhandler);
});

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