动态创建内联样式的JQuery测试

时间:2018-12-03 18:43:31

标签: jquery

我有一个element which calls a function来创建内联style属性。这个:

 <li id="Guilhem_Vidal_MSP-AU" class="highlight-entities" 
          onclick="highlightEntities(this)">Guilhem Vidal</li>

...这样说:

function highlightEntities(element) {
    $(element).css("backgroundColor", "yellow");
    $("."+ element.id).css("backgroundColor", "yellow");
    }

它可以为自己(以及许多其他元素)设置背景颜色,并且效果很好。

<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities" 
          onclick="highlightEntities(this)" style="background-color: yellow;">Guilhem Vidal</li>

现在,当用户再次单击它时,我想测试它是否已设置样式。这应该很简单:如果已设置内联style,则删除样式;如果没有style,则创建样式。

但是我的测试尝试似乎没有做任何事情:

 function highlightEntities(element) {
    var attr = ($(element).attr("style")
    if(typeof attr !== undefined && attr !== false) {
      $(element).removeAttr("style");
      $("."+ element.id).removeAttr("style");}
    else {
      $(element).css("backgroundColor", "yellow");
      $("."+ element.id).css("backgroundColor", "yellow");}
    }

看着variety of problems testing for an attribute brings,我可能测试不正确吗?

请提前谢谢。

1 个答案:

答案 0 :(得分:1)

typeof返回一个String,因此您的测试应该是:

if (typeof attr !== "undefined" && attr !== false)

否则,第一个子句的计算结果始终为true!

以下代码片段显示此修复程序使原始功能正常工作:

function highlightEntities(element) {
  var attr = $(element).attr("style");
  if(typeof attr !== "undefined" && attr !== false) {
    $(element).removeAttr("style");
    $("."+ element.id).removeAttr("style");}
  else {
    $(element).css("backgroundColor", "yellow");
    $("."+ element.id).css("backgroundColor", "yellow");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities" 
          onclick="highlightEntities(this)">Guilhem Vidal</li>
</ul>

<div class="Guilhem_Vidal_MSP-AU">Other element with class matching trigger id</div>

但是,正如@Taplar所述,推荐的方法是使用jQuery的toggleClass()ES6 classList.toggle

请注意,jQuery toggleClass与较旧的浏览器更广泛地兼容。您可以检查classList支持here

这是有无jQuery的解决方案

// Vanilla Javascript
function highlightEntities(element) {

  element.classList.toggle("highlighted");
  document.querySelectorAll("." + element.id).forEach( e => e.classList.toggle("highlighted") );

}

// jQuery
function jqHighlightEntities(element) {

  $(element).toggleClass("highlighted");
  $("." + element.id).toggleClass("highlighted");

}
.highlighted {
  background-color: yellow;
}
<ul>
<li id="Guilhem_Vidal_MSP-AU" class="highlight-entities" 
          onclick="highlightEntities(this)">Guilhem Vidal</li>
</ul>

<div class="Guilhem_Vidal_MSP-AU">Other element with class matching trigger id</div>