skip to Main Content

I am working on a click event at the front.

Click Tuesday and Thursday to activate the click function.

But I want to make it work only when I click two or four.

Please refer to the code below.

<li class="swiper">
  <span style="" class="Day">
    화<em date="2022-08-02" class="on">2</em>
  </span>
</li>
    
<li class="swiper">
  <span style="" class="Day">
    목<em date="2022-08-04">4</em>
  </span>
</li>

js click code (i try)

       $("li > span > em").click(function () {
            $("li > span > em").removeClass("on");
            $(this).addClass("on");
})

What should I do?

3

Answers


  1. Try this

    $(document).on('click', '.Day', function(){})
    
    Login or Signup to reply.
  2. Your code is working. You can check by adding alert or console.log inside the click callback function.

    $("li > span > em").click(function () {
      alert('hello');
      $("li > span > em").removeClass("on");
      $(this).addClass("on");
    })
    
    Login or Signup to reply.
  3. I think i have a solution for you ! it’s the stopPropagation() method. it prevents propagation of the same event from being called.
    Propagation means bubbling up to parent elements or capturing down to child elements.

    Try this out :

    $(" li > span > em").click(function (e) {
        alert('em CLICKED');
        e.stopPropagation();
    });
    
    $("li > span").click(function (e) {
        alert('span CLICKED');
        $("li > span > em").removeClass("on");
        $(this).addClass("on");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search