如何将活动类添加到html css中的li元素中

问题描述 投票:0回答:2

我一直在尝试选择列表项时使用有效边框。我无法获得显示CSS背景颜色的项目。如何使它正常工作...然后我要问的第二个问题是,如何在单击按钮时显示选择哪种颜色的警报?

这里是我要合并的JavaScript。

  $(".swatches li").click(function() {
        $(this).addClass('activeColor');
        $(this).removeClass('activeColor');
   });

这是我的html

<div class="dropdown-container">
  <ul class="swatches" id="swatches">
    <li class="cell">
      NONE
      <div class="colorBox"></div>
      <!--END COLOR BOX-->
    </li>
    <!--END LI-->
  </ul>
  <!--END SWATCHES-->
</div>
<!--END DROPDOWN CONTAINER-->

<div class="buttonForColor">
  <button>
    Change Color
  </button>
</div><!--END BUTTON FOR COLOR-->

css

.activeColor {
  background-color: red;
}

这是我的jsfiddlehttps://jsfiddle.net/kotten03/02abL9cu/

任何帮助将不胜感激!

javascript function class html-lists element
2个回答
0
投票

尝试下面的代码段

  var elements =   $(".swatches li");
  for (var i = 0, n = elements.length; i < n; ++i) {
  	var e = elements[i];
  	$(e).click(function() {
      console.log('working');
          $(this).addClass('activeColor');
     });
  }

0
投票

您正在添加该类,然后立即将其删除。从$(this).removeClass('activeColor');功能中删除click以停止此操作。如果要清除该类的先前项目,可以使用:

$(".swatches li").click(function() {
    $(".swatches li").removeClass('activeColor');
    $(this).addClass('activeColor');
});

alert颜色,一种选择是:

$(".buttonForColor button").click(function() {
    alert($($.find('.activeColor')[0]).text());
});
© www.soinside.com 2019 - 2024. All rights reserved.