代码之家  ›  专栏  ›  技术社区  ›  jbrehr

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

  •  0
  • jbrehr  · 技术社区  · 7 年前

    我有一个 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>
    

    现在,当用户再次单击它时,我想测试它是否已经设置了样式。这应该很简单:如果 已设置,如果没有,则删除样式 风格

    但我的测试尝试似乎没有任何效果:

     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 回复  |  直到 7 年前
        1
  •  1
  •   Zim    7 年前

    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>

    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>