javascript - trigger click event when has class jquery - Stack Overflow

admin2025-04-18  0

I want to trigger a function when has an specific class, in this case Clicked so I want to return the alert (unliked)

HTML

<div class="social">
<div class="LikePost default"></div>
</div>

JQUERY

$(".social").find(".LikePost").trigger("click"); /*when has class "clicked"*/
alert("unliked")

TRIGGERED FUNCTION

$('.LikePost').on('click', function() {
  if ($(this).hasClass("default")) {
    $(this).addClass("Clicked");
    $(this).removeClass("default");
    alert("post liked");
  } else {
    $(this).addClass("default");
    $(this).removeClass("Clicked");
    alert("post unliked");
  }
});

I want to trigger a function when has an specific class, in this case Clicked so I want to return the alert (unliked)

HTML

<div class="social">
<div class="LikePost default"></div>
</div>

JQUERY

$(".social").find(".LikePost").trigger("click"); /*when has class "clicked"*/
alert("unliked")

TRIGGERED FUNCTION

$('.LikePost').on('click', function() {
  if ($(this).hasClass("default")) {
    $(this).addClass("Clicked");
    $(this).removeClass("default");
    alert("post liked");
  } else {
    $(this).addClass("default");
    $(this).removeClass("Clicked");
    alert("post unliked");
  }
});
Share edited Mar 20, 2018 at 20:20 j08691 208k32 gold badges269 silver badges280 bronze badges asked Mar 20, 2018 at 20:15 joejoe 2191 gold badge2 silver badges12 bronze badges 2
  • 3 $(".clicked").trigger("click") ? – user1636522 Commented Mar 20, 2018 at 20:17
  • small, quick and awesome!! – joe Commented Mar 20, 2018 at 20:20
Add a ment  | 

2 Answers 2

Reset to default 2

Alright x-D

$(".Clicked").trigger("click")

You can rewrite your trigger like this:

$('.LikePost').on('click', function(){

// just invert classes state
$(this).toggleClass("default");
$(this).toggleClass("Clicked");

// if is default, its liked, if not, its not liked
if($(this).hasClass("default")) {
    alert("post liked");
} else {
    alert("post unliked");
}
});

And if you want to manually trigger all liked posts, just do it:

$('.Clicked').trigger('click');
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744951465a276361.html

最新回复(0)