0

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

2 Answers 2

1

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;?>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

Can you post your updated code? Here's the test I made to do this: jsbin.com/punifaweji/1/edit?html,js,console,output
i chane it like this:$('document').on("click", ".li_ik1",function(){ $(this).replaceWith('<img class="li_ik2" src="_pc/lkm.png"/>'); }); $('document').on("click", ".li_ik2",function(){ $(this).replaceWith('<img class="li_ik1" src="_pc/lk.png"/>'); });
Don't use quotes in the selector for document. It should just be $(document).
i test that too.your test shows only one 1,2 in console. i want change on every click
Glad to help out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.