سؤال

Is it possible to use jquery .on() method instead of .delegate() when there is no event to be listened to?

According to the .on() documentation:

.on( events [, selector] [, data] , handler(eventObject) )

The events argument is not optional.

The use of .on()/.delegate() is for elements that are added dynamically.

هل كانت مفيدة؟

المحلول

Since .on()s purpose it to attach event-handlers to a certain element, it makes absolutely no sense to use it without an event. That's why the event parameter is required.

From the doc:

Description: Attach an event handler function for one or more events to the selected elements.

نصائح أخرى

You can use custom events:(it IS still an event, but YOUR event )

markup:

<div id='mePlease'>
 <div id='noWay'>Hi</div>
</div>

$('#mePlease').on('wacky','#noWay',function(){
   alert('wackyEnough');
});
$('#noWay').trigger('wacky');

but really, this could be done with a simple function call.

The purpose of these functions is to delegate functionality to events; so no, you can't omit the events parameter from either of these function calls.

I suspect what you want is to "do stuff" to some elements that are loaded after page-load (asynchronously), no? Maybe you also need to do this stuff to elements that already exist on page-load?

In that case I suggest you wrap your declarations in a function, and call that function both on page-load and once the asynchronous call is complete.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top