As to the cause of your problem, the ajax request will update the HTML DOM tree with new HTML elements from the ajax response. Those new HTML elements do —obviously— not have the jQuery event handler function attached. However, the $(document).ready()
isn't re-executed on ajax requests. You need to manually re-execute it.
This can be achieved in various ways. The simplest way is to use $(document).on(event, selector, function)
instead of $(selector).on(event, function)
. This is tied to the document and the given functionRef
is always invoked when the given eventName
is triggered on an element matching the given selector
. So you never need to explicitly re-execute the function by JSF means.
$(document).on("change", ":input", function() {
console.log("From change event on any input: " + this.id);
});
The alternative way is to explicitly re-execute the function yourself on complete of ajax request. This would be the only way when you're actually interested in immediately execute the function during the ready
/load
event (e.g. to directly apply some plugin specific behavior/look'n'feel, such as date pickers). First, you need to refactor the $(document).ready()
job into a reusable function as follows:
$(document).ready(function(){
applyChangeHandler();
});
function applyChangeHandler() {
$(":input").on("change", function() {
console.log("From applyChangeHandler: " + this.id);
});
}
(note that I removed and simplified your completely unnecessary $.each()
approach)
Then, choose one of the following ways to re-execute it on complete of ajax request:
Use the oncomplete
attribute of the PrimeFaces command button:
oncomplete="applyChangeHandler()"
Use <h:outputScript target="body">
instead of $(document).ready()
,
<h:outputScript id="applyChangeHandler" target="body">
applyChangeHandler();
</h:outputScript>
and reference it in update
attribute:
update=":applyChangeHandler"
Use <p:outputPanel autoUpdate="true">
to auto update it on every ajax request:
<p:outputPanel autoUpdate="true">
<h:outputScript id="applyChangeHandler">
applyChangeHandler();
</h:outputScript>
</p:outputPanel>
Use OmniFaces <o:onloadScript>
instead of $(document).ready()
, <h:outputScript>
and all on em.
<o:onloadScript>applyChangeHandler();</o:onloadScript>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…