簡體   English   中英

檢查不存在的 class

[英]Сheck for a non-existent class

我有一些代碼可以更新div並添加 +1 值

$(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)
     },
    });
  });
});

單擊時,我添加了 class active$(this).addClass('active'); 並且成功發生了一個動作,當我再次單擊時,再次觸發此動作,因此我需要檢查僅當active succes不存在時才應執行此動作

我試着用這種方式檢查

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)
        }
     },

但這不起作用,沒有錯誤,只是沒有添加值+1

原則上,這就是添加喜歡的系統對我有用的方式

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>

當您單擊like-button時,此代碼

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

將 +1 添加到該值並更新該數字為 +1 的 div,但現在事實證明,如果我們再次單擊,我們會得到另一個 +1,依此類推。 我需要確保僅在第一次單擊時添加 +1,為此我嘗試使用活動的 class,並檢查它是否處於活動狀態,然后我們不再添加

我認為你的問題是你總是添加“活動” class ,不僅是在成功的情況下。

此外,您在所有 div 周圍都有錨點。 這可能會導致單擊 div 會使this成為 div 而不是錨點。

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

這部分是否正確。 問題是您需要確定錨點是否始終是目標元素,而與您單擊的位置無關。

這是一個工作示例:

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');
      }
    });
});

我創建了一個 jsfiddle,因此您可以使用它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM