javascript - .addClass().removeClass() 的问题

标签 javascript jquery css

昨晚我花了几个小时试图找出这里出了什么问题,但没有成功。 我有一个 div,单击它会展开并创建一个关闭按钮,该按钮会将 div 返回到其原始状态。我通过添加和删除类来做到这一点。我遇到的问题是,当单击原始 div (.talent) 时,它确实会更改以填充包含的 div。但是,当单击按钮 (.btn) 时,div 不会返回到其原始状态。

JS-

$(".talents .talent").click(function(){
  if ($(this).hasClass("talent")) {
    $(this)
      .removeClass("talent")
      .addClass("tree")
      .append("<div class=\"close btn\">X</div>");

    $(".tree .btn").click(function(){
      console.debug("WORKING!?!?!?");
      $(".tree").addClass("talent");
      $(".tree").removeClass("tree");
      $(".talents .talent").show();
      $(this).remove();
    });
    $(".talents .talent").hide();
  }
});

CSS -

.talents{
  border:1px solid white;
  border-radius:10px;
  overflow:hidden;

  height:165px;

  margin:10px;
}

.talents .talent{
  text-align:center;
  font-size:2.4em;
  height: 50px;
  width: 50px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  display: inline-block;
  border: 3px solid white;
  border-radius: 15px;
  margin: 5px 7px 5px 7px;
}

.tree{
  position:relative;

  width:100%;
  height:100%;
}

最佳答案

$(".talents .talent").click(function(){
  if ($(this).hasClass("talent")) {

以上代码的计算结果总是为真

如果你想让它更好地工作,任何具有人才等级的元素也应该有另一个等级,并且像这样工作(我会说使用 .tree 作为 .other_class 但如果没有看到 html 就不能 100% 确定):

$(".talents .other_class").click(function(){
  if ($(this).hasClass("talent")) {

另外,最好将 btn 点击处理程序放在第一个点击处理程序之外。

关于javascript - .addClass().removeClass() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18086157/

相关文章:

javascript - 无法从动态 html 代码中读取 null 的属性 'style'

javascript - 如何在 jQuery 中识别元素是否靠近浏览器窗口的顶部

html - 文档中正确的 CSS 定位

css - 我如何在 Chrome 中的 css 转换顶部使用 DIV 的悬停效果? (在 FF 中有效)

html - 如何确保长文本在圆形内水平和垂直居中

javascript - 使用 jQuery 单击操作后重新启动功能

javascript - Whatsapp 分享按钮 - 分享网址不正确

javascript - 参数不应该为空

asp.net-mvc-3 - MVC 3 - Html.EditorFor 似乎在 $.ajax 调用后缓存旧值

php - 从多个相同的表单字段插入数据