简体   繁体   中英

jQuery click handler not working

I can't get the following function to work.

On click of class .image, content in 3 divs (gallerytext, image, and thumbset) is to be replaced. I have been trying to get this to work for days now and I cannot figure out what I am doing wrong.

My code:

     // Init load 
  $(document).ready(function() {
        var $doc = $(document.body);


        var text = $('#gallerytext1').html();  //blank divs are filled with content on page load 
        $('#gallerytext').html(text);
        var thumbset = $('#thumbset1').html();
        $('#thumbset').html(thumbset);  
        $('#image').html('<img src="images/edwards1.jpg" border="0"/>');


    //click handler
       $doc.on("click",".image",function(){

        var image=$(".image").attr("rel"); 
        var imid=$(".image").attr("data");
        var text=$('#gallerytext'+imid).html();
        var thumbset=('#thumbset'+imid).html();

        $('#debug').html(imid);

        $('#gallerytext').fadeIn('slow');
        $('#gallerytext').html(text);
        $('#thumbset').fadeIn('slow');
        $('#thumbset').html(thumbset);
        $('#image').hide();                 
        $('#image').fadeIn('slow');
        $('#image').html('<img src="' + image + '"/>');
        return false;


      });
  });

The initial content loads just fine but I cannot get the click handler to work. Objects with the class .image are formatted as such:

<a href="#" rel="images/edwards2.jpg" data="1" class="image image2"><img src="images/edwardsthumb2.jpg" class="thumb" border="0"/></a>

Any assistance would be highly appreciated, thank you.

These are probably your problematic lines:

var image=$(".image").attr("rel"); 
var imid=$(".image").attr("data");

$(".image") selects all of the elements with a class of image . You want just the one that was clicked, so use this to refer to it:

var image = $(this).attr("rel"); 
var imid = $(this).attr("data");

Also, don't make up custom attributes like data . HTML5 introduced data- attributes which are used to store custom data types, so use them:

data-number="1"

And you can access it with the .data() method:

var imid = $(this).data('number');

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