Selecting multiple elements with Jquery, but adding a class only to one of them with addClass()

问题: I have a few divs with the 'clickable' class. If one of the divs is clicked, then i want the class 'clicked' to be added to the element, but only to that particular div tha...

问题:

I have a few divs with the 'clickable' class. If one of the divs is clicked, then i want the class 'clicked' to be added to the element, but only to that particular div that was clicked. Currently my code adds the class to all elements with the 'clickable' class, since i'm selecting all of them. How do i add it only to the specific div that was clicked, without writing code for each div?

HTML:

<div class="size m-size clickable">M</div>
<div class="size m-size clickable">L</div>
<div class="size m-size clickable">XL</div>
<div class="size m-size clickable">XXL</div>

Jquery:

$('.clickable').on('click', function () {
    $('.clickable').addClass('clicked');
})

回答1:

Change the code to:

$('.clickable').on('click', function () {
    $(this).addClass('clicked');
})

Where "$(this)" corresponds to the event target element.

You can also look into the toggleClass() function.

  • 发表于 2019-12-25 16:15
  • 阅读 ( 114 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除