javascript - jquery click handler only fires once -


Images used to show / hide content under a heading

  & lt;! DOCTYPE html & gt; & Lt; Html & gt; & Lt; Body & gt; & Lt; H2 & gt; Title & lt; / H2 & gt; & Lt; P & gt; Content & lt; / P & gt; & Lt; / Body & gt; & Lt; / Html & gt; $ (Document) .ready (function () {var $ imag = $ ("& lt; img src = 'arrow_down.jpg' & gt;"); var $ imag2 = $ ("& lt; img src = 'arrow_up $ ($ Imag); $ ($ imag) .on ("click", function () {$ ("p"). Hide (); ($ imag) $ (" $ ($ Imag2) .on ("click", function () {$ ("p"). Show (); ($ imag2) .remove () ; $ ("H2"). Attachments ($ imag);});}); $ (document) main (ready);  

The first time you click on the images click But the next time you click on it, this page will not even be without refreshing. The reason for this is that item handlers such as click () should be linked to elements that are already in DOM when the page is loaded for elements that are later added It has to be accrued from a constant fundamental element using () on it, such as:

  $ (document) .on ("click", $ imag, function) { $ ("P"). Hide (); ($ imag) .remove (); $ ("h2"). Attachments ($ imag2);}); $ (Document) .on ("click", $ imag2, function () {$ ("p"). Show (); ($ imag2) .remove (); $ ("h2"). Append ($ imag) ;});  

Just added one adjustment because I was not sure that it would work with $ $ imag / $ imag2 (not this) Instead, you should add classes to your images, e.g. Such as:

  var $ imag = $ ("& lt; img class = 'below' src = 'arrow_down.jpg' & gt;"); Var $ imag2 = $ ("& lt; img square = 'top' src = 'arrow_up.jpg' & gt;"); Adjusted code  
  $ (document) .on on ("click", '.down', function () {$ ("p") with  

.hide (); $ ('down'). Remove (); $ ("h2"). Attachments ($ imag2);}); $ (Document) .on ("click", '.up', function () {$ ("p"). Show (); $ ('up up'). Remove (); $ ("h2") attached ($ Imag);});

For reference, the "Direct and Assigned Event" section:

"Event handlers are bound only for currently selected elements; When your code calls to call .on (). "


Comments

Popular posts from this blog

apache - 504 Gateway Time-out The server didn't respond in time. How to fix it? -

c# - .net WebSocket: CloseOutputAsync vs CloseAsync -

c++ - How to properly scale qgroupbox title with stylesheet for high resolution display? -