jQuery toggle() with toggleClass()

泪湿孤枕 提交于 2020-01-06 12:49:40

问题


I have a button that toggles a DIV layer on and off. I am trying to add a class to the button so that when its toggled on it appears differently, however I haven't been able to get it working, the class is not being added when the button is toggled.

The button is a list item e.g. On / Off

Here is my code:

$("#btninformation").click(function () {
  $("#map-items-category-one").toggle("slow", function() {
    $(this).toggleClass("toggled-on");
  });
});

Any ideas whats wrong with it?

Thanks Zach


回答1:


You're toggling the class on the '#map-items-category-one', not on the '#btninformation'. Just grab a reference to the button outside of the inner callback:

$("#btninformation").click(function () {
  var $that = $(this);
  $("#map-items-category-one").toggle("slow", function() {
    $that.toggleClass("toggled-on");
  });
});


来源:https://stackoverflow.com/questions/5198138/jquery-toggle-with-toggleclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!