SoFunction
Updated on 2025-03-06

Prebinding of event for jQuery

1. Prebind

First, let’s explain what prebinding is. Prebinding, as the name suggests, is to bind events before the control on the web page appears. Prebinding mainly refers to the .on() method in jQuery.

2. Demo

HTML code

<div >
<input type="button"  value="test"/>
</div>

General jQuery code:

$('#root').find('#test').on('click', function() {
...
});

Prebined jQuery code:

$('#root').on('click', '#test2', function() {
...
});

jQuery code to add control

$('#root').append('<input type="button"  value="test2"/>')

Explanation: When the page control is displayed directly, such as 'test', the above two methods of binding control events are fine and can work normally. However, if the above HMTL code is in a template, such as jsview, the template data is not added when the page is loaded, or the above HTML code is not on the page at the beginning, but is added through jQuery. For example, test2 is a control added at a certain moment after the page is loaded, using the general code to bind control events will have problems. You will find that the control has no bound events, and using the pre-binding method, the control events can be bound, even if the control is added later.

The above content is the event prebinding of jQuery, and the jQuery document address is:/on/

The above is the prebinding of jQuery incident introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!