简体   繁体   中英

how make a .click() function reusable

Essentially, i have been unable to find a way to make the following .click() work more than once. My intent is to make is so that repeating clicks of the .gen2 class will continually .remove() the current .gen2 image and replace it with a randomly selected image from myArray.

$(document).ready(function(){
  $('.gen2').click(function(){
    $('.gen2').remove();
    var myArray = ['<img class="gen2" src="images/bottom/chinchilla.png" />', 
    '<img class="gen2" src="images/bottom/bird.png" />', 
    '<img class="gen2" src="images/bottom/bluejay.png" />',  
    '<img class="gen2" src="images/bottom/walrus.png" />'];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    $('.change').append(rand);
});
  $('.gen1').click(function(){
    $('.gen1').remove();
    var array = ['<img class="gen1" src="images/top/raven.png" />', 
    '<img class="gen1" src="images/top/boar.png" />', 
    '<img class="gen1" src="images/top/trex.png" />'];
    var rand = array[Math.floor(Math.random() * array.length)];
    $('.change').append(rand);
});});

HTML is as follows. because the positions of both .gen1 and .gen2 are set to absolute, they overlap so that as each is removeed and proceedurally replaced with .append(), a new image is formed.

<body>
    <div class="change">
        <img class="gen1" src="images/top/raven.png" />
        <img class="gen2" src="images/bottom/chinchilla.png" />
    </div>

the problem is that after the first click(); the function no longer runs. I can't figure how..

Thanks!

  1. Use Object to store the images sources
  2. Store only images source URL in object of arrays. Don't add HTML
  3. Use data- custom attribute on the image to store custom data
  4. Don't remove and add HTML elements in DOM. Update the src value of the element.
  5. Add Common class to bind events on elements

Note: As the image is picked randomly, there are chances when the image may not change on click ie image is changed but next image is same as previous.

 var obj = { 'gen1': ['', 'images/top/boar.png', 'images/top/trex.png' ], 'gen2': ['http://www.ggdesignsembroidery.com/store/images/uploads/Chubby1.jpg', 'http://www.ggdesignsembroidery.com/store/images/uploads/Chubby2.jpg', 'http://www.ggdesignsembroidery.com/store/images/uploads/Chubby3.jpg', 'http://www.ggdesignsembroidery.com/store/images/uploads/Chubby4.jpg' ] }; $('.change').on('click', '.gen', function() { var myArray = obj[$(this).data('target')]; var rand = myArray[Math.floor(Math.random() * myArray.length)]; $(this).attr('src', rand); }); 
 img { height: 100px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div class="change"> <img class="gen1 gen" src="images/top/raven.png" data-target="gen1" /> <!-- ^^^: Common Class ^^^^^^^^^^^: Custom Attribute --> <img class="gen2 gen" src="http://www.ggdesignsembroidery.com/store/images/uploads/Chubby1.jpg" data-target="gen2" /> <!-- ^^^: Common Class ^^^^^^^^^^^: Custom Attribute --> </div> 

Images taken from http://www.ggdesignsembroidery.com/

You want to listen dynamically added elements , so you need to use event delegation

 $(document).ready(function() { var myArray = ['<img class="gen2" src="images/bottom/chinchilla.png" />', '<img class="gen2" src="images/bottom/bird.png" />', '<img class="gen2" src="images/bottom/bluejay.png" />', '<img class="gen2" src="images/bottom/walrus.png" />' ], array = ['<img class="gen1" src="images/top/raven.png" />', '<img class="gen1" src="images/top/boar.png" />', '<img class="gen1" src="images/top/trex.png" />' ]; $('.change').on('click', '.gen2', function() { $('.gen2').remove(); var rand = myArray[Math.floor(Math.random() * myArray.length)]; $('.change').append(rand); }).on('click', '.gen1', function() { $('.gen1').remove(); var rand = array[Math.floor(Math.random() * array.length)]; $('.change').append(rand); }); }); 

Try this:

$(document).ready(function(){
    $(document.body).on('click','.gen2',function(){
      //your code here
    });
    $(document.body).on('click','.gen1',function(){
      //your code here
    });
});

I think this is a better approach and may be you can combine the two with more generic selector like $('.change>img')

$(document).ready(function(){
  $('.gen2').click(function(){
    var myArray = ["images/bottom/chinchilla.png" ,"images/bottom/bird.png" ,"images/bottom/bluejay.png","images/bottom/walrus.png" ];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
     $(this).attr("src",rand);
});
  $('.gen1').click(function(){
    var array = ["images/top/raven.png" ,"images/top/boar.png","images/top/trex.png"];
    var rand = array[Math.floor(Math.random() * array.length)];
     $(this).attr("src",rand);
});});

You would need to rebind the click event, because the initial binding was deleted when you removed the image.

Hope this code helps

$(document).ready(function(){

    $('.gen2').click(gen2);
    $('.gen1').click(gen1);

    function gen2(){
        $('.gen2').remove();
        var myArray = ['<img class="gen2" src="images/bottom/chinchilla.png" />', 
                       '<img class="gen2" src="images/bottom/bird.png" />', 
                       '<img class="gen2" src="images/bottom/bluejay.png" />',  
                       '<img class="gen2" src="images/bottom/walrus.png" />'];
        var rand = myArray[Math.floor(Math.random() * myArray.length)];
        $('.change').append(rand);
        $('.gen2').click(gen2);
    }

    function gen1(){
         $('.gen1').remove();
        var array = ['<img class="gen1" src="images/top/raven.png" />', 
                     '<img class="gen1" src="images/top/boar.png" />', 
                     '<img class="gen1" src="images/top/trex.png" />'];
        var rand = array[Math.floor(Math.random() * array.length)];
        $('.change').append(rand);
        $('.gen1').click(gen1);
    }
});

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