Jquery - 点击时改变颜色

Jquery - Change colour when click

当我点击时,我放置了高亮,但我希望当我再次点击时,高亮消失,或者当我点击一个按钮时,他删除了最后一个高亮。

$('div').each(function() {
  var $this = $(this);
  $this.html($this.text().replace(/\b(\w+)\b/g, "<span></span>"));
});

$('div span').click(function() {
  $(this).css('background-color', '#ffff66');
});
span {
  font-size: 15pt;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<div>
  <span>This text is a test text</span>
</div>

在他去掉高亮的词中,我再次点击时如何放置特征?

感谢您的帮助。

您可以创建一个 class 并使用 toggleClass 切换它。

$('div').each(function() {
  var $this = $(this);
  $this.html($this.text().replace(/\b(\w+)\b/g, "<span></span>"));
});

$('div span').click(function() {
  $(this).toggleClass('highlightSpan');
});
span {
  font-size: 15pt;
}

.highlightSpan {
  background-color: #ffff66;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<div>
  <span>This text is a test text</span>
</div>