【问题标题】:jQuery - Add class to each span that uses more than one linejQuery - 将类添加到使用多于一行的每个跨度
【发布时间】:2015-07-31 06:03:21
【问题描述】:

我在这段代码上有点卡住了,所以我希望你能帮助我,这个问题可以帮助其他人:)

我想要完成的是将一个类添加到一个多于一行的跨度的 parent().parent() (我不知道如何用英语称呼它)。 为了查看跨度是否使用多条线,我决定测量跨度的高度。如果跨度高于 25px,那么我肯定知道它使用了不止一行。对于与该条件匹配的每个跨度,我想向 parent().parent() 添加一个类,以便我可以使用 css 对其进行样式设置。

我的 html 看起来像这样:

<li><label><span class="abc-span">a</span><span class="text-that-is-measured">blablablablabla</span></label></li>
<li><label><span class="abc-span">b</span><span class="text-that-is-measured">blablablablabla</span></label></li>
<li><label><span class="abc-span">c</span><span class="text-that-is-measured">blablablablabla</span></label></li>

我的脚本如下所示:

var items = [];
$('span.text-that-is-measured').each(function (i, e) {
  items.push($(e));
});

for (var i = items.length - 1; i >= 0; i--) {
    console.log(items[i]);
    var spanheight = $(items[i]).height();
    if ( spanheight > 30) {
        $(items[i]).parent().parent().addClass('exampleclass');
    }
};

问题是只会给第一个匹配条件的li 一个类“exampleclass”,我希望它在每个 li

有人知道我做错了什么吗?

我希望我的解释足够清楚,英语不是我的第一语言。

提前致谢!


感谢大家的解释和帮助!

【问题讨论】:

  • parent().parent() -> 祖父母?或者任何不是父母的祖先?
  • 注意,可以比较元素的行高,而不是硬编码的值,比如30

标签: jquery arrays each parent


【解决方案1】:

您可以使用.filter() 函数获取高度大于30px 的跨度以及.closest('li') 以获取最接近的li(您指的是parent().parent()):

$('span.text-that-is-measured').filter(function(){
    return $(this).height() > 30; //for height higher than 30
}).closest('li').addClass('exampleclass');//add class to li element

【讨论】:

    【解决方案2】:

    你需要使用closest来获取祖先li

    试试这个:

    $('span.text-that-is-measured').each(function(i, e) {
        if ($(this).height() > 30) {
            $(this).closest('li').addClass('exampleclass');
        }
    });
    

    【讨论】:

      【解决方案3】:

      您可以使用.closest() 获取祖先li,然后使用.siblings() 查找其他li 元素。

      var targetListItem = $("span.text-that-is-measured").filter(function() {
          return $(this).height() > 25;
      }).closest("li");
      targetListItem.addClass("exampleclass");
      targetListItem.siblings().addClass("exampleclass");
      

      这有点啰嗦。您可以使用曾祖父母的.children(),而不是使用span 的祖父母。

      $("span.text-that-is-measured").filter(function() {
          return $(this).height() > 25;
      }).closest("li").parent().children().addClass("exampleClass");
      

      这两个示例都基于具有父 ul 或类似元素的 li 元素。

      【讨论】:

        【解决方案4】:

        以下代码将适用于您想要做的事情:

        $('span.text-that-is-measured').each( 
            function (i, e) {  
                var spanHeight= $(e).height();  
                if ( spanHeight > 30) {
                    $(e).closest('li').addClass('exampleclass');
                }
        })
        

        【讨论】:

          猜你喜欢
          • 2021-07-28
          • 1970-01-01
          • 2011-04-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多