【问题标题】:if Innerhtml length is greater, add class to its element如果 Innerhtml 长度更大,则将类添加到其元素
【发布时间】:2013-05-22 14:43:31
【问题描述】:

我希望它控制每个 LI A 内的文本长度,如果它大于 5,则自动将一个类“long”添加到其对应的 LI。到目前为止,我有这个,但没有工作:

html:

<ul id="menu">
    <li><a href="">Kodu</a></li>
    <li><a href="">VägaPikkSõna</a></li>
    <li><a href="">Teenused</a></li>
    <li><a href="">Kontakt</a></li>
</ul>

脚本:

$(document).ready(function(){
    var x = document.getElementById('menu').getElementsByTagName('a');

    for(i=0; i<x.length; i++){              
        if(x[i].innerHTML.length > 5){
            $(this).parent().addClass('long')
        }
    }
});

【问题讨论】:

    标签: jquery parent innerhtml addclass


    【解决方案1】:
    $(document).ready(function(){
        $('#menu a').addClass(function() {
            return this.innerHTML.length > 5 ? 'long' : '';
        });
    });
    

    FIDDLE

    【讨论】:

      【解决方案2】:

      试试这个:

      $(document).ready(function(){
          $("#menu a").each(function() {
              if($(this).text().length>5){
                  $(this).parent().addClass('long');
              }
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-25
        • 2013-01-06
        • 1970-01-01
        • 2018-02-10
        • 2015-02-08
        • 2020-10-06
        • 2011-03-24
        • 1970-01-01
        相关资源
        最近更新 更多