11111111111111111
11111111111111111

Reputation: 158

jquery - change between two html element on click

i have two html element and i want to change it with another by clicking on one. this is my code and it works but one time:

<div class="ic_lk"></div>
<?php $pic=0;?>
<script>
$('document').ready(function(){
    var pic= <?php echo $pic;?>;
if(pic==0) {
        $('.ic_lk').html('<img class="li_ik1" src="_pc/lk.png"></img>'); 
        }else if(pic>0){
        $('.ic_lk').html('<img class="li_ik2" src="_pc/lkm.png"></img>'); 
    }

$(".li_ik1").on("click",function(){
    $(this).replaceWith('<img class="li_ik2" src="_pc/lkm.png"/>');
    });
$(".li_ik2").on("click",function(){
    $(this).replaceWith('<img class="li_ik1" src="_pc/lk.png"/>');
    });
}); 
</script>

thanks

Upvotes: 0

Views: 59

Answers (2)

MichaelvE
MichaelvE

Reputation: 2578

Your listener is being set only on document ready, however your element is not present yet. So you have to add the listener after you add the element:

$('document').ready(function() {
  var pic = 0; //<?php echo $pic;?>;
  if (pic == 0) {
    $('.ic_lk').html('<img class="li_ik1" src="https://picsum.photos/200/200?image=1" />');
    setPic1();
  } else if (pic > 0) {
    $('.ic_lk').html('<img class="li_ik2" src="https://picsum.photos/200/200?image=2" />');
    setPic2();
  }
});

function setPic1() {
  $(".li_ik1").on("click", function() {
    $(this).replaceWith('<img class="li_ik2" src="https://picsum.photos/200/200?image=2"/>');
    //
    setPic2();
  });
}

function setPic2() {
  $(".li_ik2").on("click", function() {
    $(this).replaceWith('<img class="li_ik1" src="https://picsum.photos/200/200?image=1"/>');
    //
    setPic1();
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ic_lk"></div>
<?php $pic=0;?>

Upvotes: 1

Doug F
Doug F

Reputation: 884

Since .li_ik2 is dynamic, meaning that it's not on the page at the time of page load, the second bind won't work. As outlined here, you should do something like this:

$(document).on("click", ".li_ik2", function(){

But of course, check which version of JQuery you have first.

Upvotes: 0

Related Questions