繁体   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