Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - Function doesn't work after appending new element

I have a problem with the "click" action on a new element created by a jQuery function, it doesn't work.

I created a JSFiddle to this link (JSFiddle), but it doesn't work perfectly because I can't call a Ajax request in JSFiddle.

I have these two buttons,

<input type="button" onclick="invia('SIC-034031','', 's');" value="AGGIUNGI" style="height: 20px; width: 110px; background-color: #A5EFC5 ; color: #000000; font-family: Arial,Helvetica,sans-serif; font-size: 12px; background-repeat: no-repeat; background-position: left center;" id="iscriviSIC-034031" class="pulsanteIscrizioni" name="xaggiorna"/>&nbsp;
<input type="button" onclick="invia('SIC-034031','R', 's');" value="RISERVA" style="height: 20px; width: 110px; background-color: #F00000; color: #FFFFFF; font-family: Arial,Helvetica,sans-serif; font-size: 12px; background-repeat: no-repeat; background-position: left center;" id="iscriviRSIC-034031" class="pulsanteIscrizioni" name="xaggiorna"/>

When you call the ajax function for the first time, button one answers with this output:

OK;I;SIC-034031

Button two is only used to erase. Button one creates.

<input id="iscriviSIC-034031" class="pulsanteIscrizioni" type="button" name="xaggiorna" style="height: 20px; width: 110px; background-color: #03F; color: #FFF; font-family: Arial,Helvetica,sans-serif; font-size: 12px;" value="TOGLI" onclick="invia('SIC-034031','');">

When I click this new button, the ajax function return this,

OK;C;SIC-034031;;

Button one goes away and button two comes back. Now there is where the problem is, if I click on the first button, everything works. If I click in the second button, it doesn't work.

Can you try to help me to find the problem, please?

Thanks ;)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

$(".pulsanteIscrizioni").on("click", function()

is what you have now. Change it to -

$(document).on("click", '.pulsanteIscrizioni',function()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...