Jquery click function only fires once

2019-09-18 08:28发布

问题:

I'm using a flip book plugin, Jquery Booklet and one of the functions is to go to a specific page in the Flipbook.

.booklet("gotopage", index)

I am making a modal that contains a small thumbnail layout where I want the ability to click on a thumbnail, close the modal and the Booklet page will open to the specific page the image is on. I am trying the following code which works the first time but not subsequent times. Any help would be appreciated!

 $('.item a .counter').click(function(e){
   e.preventDefault();
   var gotoimage = $(this).text();
    $('#mybook').booklet("gotopage", gotoimage);
    $('#thumbs').modal('hide');
   });

回答1:

May be your modal is getting injected dynamically to DOM, after your binding occurs, You can use some delegation in this case,

 $(document).on('click','.item a .counter',function(e){
   var gotoimage = $(this).text();
    $('#mybook').booklet("gotopage", gotoimage);
    $('#thumbs').modal('hide');
    return false;
   });


回答2:

Are the $('.item a .counter')'s being loaded dynamically? Or are they all loaded in the page at the beginning?

If they are loaded after the page is loaded, you should try .live instead of .click

Do you have this in a jsfiddle or something?



回答3:

After some frustration with my original code I figured out how to do this using this code:

$(".item a").click(function () {
var index = $(".item a").index(this) + 2;
$('#mybook').booklet("gotopage", index);
$('#thumbs').modal('hide');
return false;
});

Since my Thumb gallery and the Booklet Flipbook have the same index # of images, it worked. I just needed to add the + 2 because I realized the Booklet has a front and back cover so I needed to have the index start 2 numbers up, rather than 0 based.