简体   繁体   中英

jQuery click handler only fires once

Appended images used as buttons to show/hide content below a heading:

<!DOCTYPE html>
<html>
<body>
    <h2>
        the heading 
    </h2>
    <p>
        the content
    </p>
</body>
</html>


$(document).ready(function () {
var $imag = $("<img src='arrow_down.jpg'>");
var $imag2 =  $("<img src='arrow_up.jpg'>");
$("h2").append($imag);

$($imag).on("click", function(){
    $("p").hide();
    ($imag).remove();
    $("h2").append($imag2);
});
$($imag2).on("click", function () {
    $("p").show();
    ($imag2).remove();
    $("h2").append($imag);
});
});

$(document).main(ready);

At first the images work when clicked. but the next time you click it, it doesn't without having to refresh the page. Why?

This is because event handlers like click() have to be appended to elements that are already in the DOM when the page is loaded. For elements that are added later the event has to be delegated from a static parent element using on(), like:

$(document).on("click", $imag, function(){
  $("p").hide();
  ($imag).remove();
  $("h2").append($imag2);
});
$(document).on("click", $imag2, function () {
  $("p").show();
  ($imag2).remove();
  $("h2").append($imag);
});

Just added a Fiddle with an adjustment as I wasn't sure if this would work with the variables $imag / $imag2 (it doesn't). Instead you should just add classes to your images, eg like this:

var $imag = $("<img class='down' src='arrow_down.jpg'>");
var $imag2 =  $("<img class='up' src='arrow_up.jpg'>");

with adjusted code

$(document).on("click", '.down', function(){
  $("p").hide();
  $('.down').remove();
  $("h2").append($imag2);
});
$(document).on("click", '.up', function () {
  $("p").show();
  $('.up').remove();
  $("h2").append($imag);
});

For reference: https://api.jquery.com/on/#on-events-selector-data-handler , section "Direct and delegated events":

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM