首页 > 解决方案 > 动态创建的内联样式的 JQuery 测试

问题描述

我有一个元素,它调用一个函数来创建内联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");}
    }

看看测试一个属性带来的各种问题,我可能没有正确测试?

可能会提前感谢。

标签: jquery

解决方案


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

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

否则,第一个子句总是评估为真!

这是一个片段,显示此修复使原始功能正常工作:

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 所述,推荐的方法是使用 jQuerytoggleClass()ES6classList.toggle

请注意,jQuerytoggleClass更广泛地与旧浏览器兼容。您可以在此处classList查看支持。

这是一个有和没有 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>


推荐阅读