【问题标题】:jQuery selector to obtain li object from specific unordered listjQuery 选择器从特定的无序列表中获取 li 对象
【发布时间】:2009-08-25 22:06:48
【问题描述】:

我正在尝试从无序列表中获取特定的 li 元素。

我是这样做的:

var listItem = $('ul.selectedItems').filter(list[i].ID);

知道为什么这不起作用吗?

【问题讨论】:

    标签: jquery css-selectors


    【解决方案1】:

    filter 方法采用常规 jQuery 选择器,因此您应该编写 filter("#"+list[i].ID)。 (假设list[i].IDid 元素的id 属性)。此外,filter 方法搜索 jQuery 对象中包含的元素,而不是它们的子元素;您应该改为调用 children 方法。请参阅documentation


    但是,最好的方法是这样的:

    var listItem = $('ul.selectedItems li#' + list[i].ID);
    

    有关 jQuery 选择器的更多信息,请参阅here

    【讨论】:

      【解决方案2】:

      这只会返回 ul,你的选择器应该返回 li's

      var listItem = $('ul.selectedItems li').filter(list[i].ID);
      

      但是如果你有 li 的 id 你可以这样做

      var listItem = $('#' + liId);
      

      【讨论】:

        【解决方案3】:

        我认为你可以这样做:

          $("ul.selectedItems li").each(function(){
            if ($(this).is('#mypreferedid')) {
               //do something here
               return false; //to stop cycling
            }
          });
        

        如果你不知道元素的 id,但你知道它的位置,你可以这样做:

          $("ul.selectedItems li").each(function(index, element){
            if (index == selectedPosition) {
               //do something here
               return false; //to stop cycling
            }
          });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-06
          • 2011-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-01
          相关资源
          最近更新 更多