简体   繁体   中英

Сheck for a non-existent class

I have some code that updates div and adds +1 value

$(function() {
  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
    },
  });

  $('.like-button').on('click', function(event) {
    event.preventDefault();
    var targetElement=$(this);
    $(this).addClass('active');

    let href = $(this).attr('href');

    $.ajax({
      url: href,
      type: 'POST',
      success: function() {
        var current = parseInt(targetElement.find('.comments-sub-header__item-icon-count').html());
          targetElement.find('.comments-sub-header__item-icon-count').html(current+1)
     },
    });
  });
});

On click, I add the class active , $(this).addClass('active'); and an action occurs which in succes , when I click again, this action is triggered again, so I need to check that such an action should be done only when the active class does not exist

I try to check this way

success: function() {
        if (targetElement.hasClass('active')) { 
          return false;
        }

        else {
          var current= parseInt(targetElement.find('.comments-sub-header__item-icon-count').html());
          targetElement.find('.comments-sub-header__item-icon-count').html(current+1)
        }
     },

But this does not work, there are no errors, just the value +1 is not added

This is how, in principle, the system for adding likes works for me

Route::post('article/{id}', 'App\Http\Controllers\ArticleController@postLike');
public function postLike($id, Request $request) {
        $article = Article::find($id);

        if(!$article){
            return abort(404);
        }

        $type = $request->input('type');
      
        if ($article->hasLikedToday($type)) {
            return response()
                ->json([
                    'message' => 'You have already liked the Article '.$article->id.' with '.$type.'.',
                ]);
        }
    
        $cookie = $article->setLikeCookie($type);
      
        $article->increment("like_{$type}");
    
        return response()
            ->json([
                'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
                'cookie_json' => $cookie->getValue(),
            ])
            ->withCookie($cookie);
    }
public function hasLikedToday(string $type)
    {
        $articleLikesJson = Cookie::get('article_likes', '{}');

        $articleLikes = json_decode($articleLikesJson, true);

        if (!array_key_exists($this->id, $articleLikes)) {
            return false;
        }

        if (!array_key_exists($type, $articleLikes[$this->id])) {
            return false;
        }

        $likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$this->id][$type]);

        return ! $likeDatetime->addDay()->lt(now());
    }

    public function setLikeCookie(string $type)
    {
        $articleLikesJson = Cookie::get('article_likes', '[]');

        $articleLikes = json_decode($articleLikesJson, true);

        $articleLikes[$this->id][$type] = now()->format('Y-m-d H:i:s');

        $articleLikesJson = json_encode($articleLikes);

        return cookie()->forever('article_likes', $articleLikesJson);
    }
<a href="/article/{{ $article->id }}?type=heart" class="comments-sub-header__item like-button {{ $article->hasLikedToday('heart') ? 'active' : '' }}">
    <div class="comments-sub-header__item-icon">
        <div class="comments-sub-header__item-icon-count">
            {{ $article->like_heart }}
        </div>
    </div>
</a>

<a href="/article/{{ $article->id }}?type=finger" class="comments-sub-header__item like-button {{ $article->hasLikedToday('finger') ? 'active' : '' }}">
    <div class="comments-sub-header__item-icon">
        <div class="comments-sub-header__item-icon-count">
            {{ $article->like_finger }}
        </div>
    </div>
</a>

When you click on the like-button , this code

var current = parseInt(targetElement.find('.comments-sub-header__item-icon-count').html());
targetElement.find('.comments-sub-header__item-icon-count').html(current+1)

adds +1 to the value and updates the div in which this number is +1, but now it turns out that if we click again, we get another +1, and so on. I need to make sure that +1 is added only on the first click, for this I try to use the active class, and make a check that if it is active, then we no longer add

I think on of your problems is that you add the "active" class always, not only if success is achieved.

Also, you have the anchor around all the divs. That could cause that clicking on the div could make the this be the div and not the anchor.

if (targetElement.hasClass('active')) {

This part if correct. The problem is you need to be sure if the anchor is always the targe element independently of where you click.

Here is a working example:

HTML

 <a href="#" class="like-button">Like
  <div class="comments-sub-header__item-icon">
    <div class="comments-sub-header__item-icon-count">0</div>
  </div>
</a>

JS

$(function() {

  $('.like-button').on('click', function(event) {
    event.preventDefault();
    var targetElement = $(this);

   
    if (targetElement.hasClass('active')) {
        console.log("is active");
      return false;
    } else {
        console.log("is not active");
      var counter = targetElement.find('.comments-sub-header__item-icon-count');
      var current = parseInt(counter.html());
      console.log(current);
      
      counter .html(current + 1)
      
        $(this).addClass('active');
      }
    });
});

I created a jsfiddle so you can play around with it.

https://jsfiddle.net/shizus/wqa4782z/1/

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