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

使用jQuery[duplicate]选择具有特定a类的元素的正确方法是什么

  •  1
  • Austin  · 技术社区  · 8 年前

    这个问题已经有了答案:

    我试图使用jQuery来选择一个div元素,但是,对于我来说,我不知道如何让它工作。我正在尝试设置它,因此当用户单击 span 类中的元素 remove 找到最接近的 div 类中的元素 class-i-want-to-select

    此代码块在页面加载完成后动态添加:

    <div class="container">
       <div>
          <span style="float:left;">some text</span>
          <span class="remove" style="float:right;">[X]</span> ///user clicks here
       </div>
       <div style="clear:both;"></div>
       <div class="class-i-want-to-select"></div> ///want to select this element
    </div>
    

    这是我试图使用的代码:

    $('body').on('click', '.remove', function () {
        var that = $(this).closest('div').find('.class-i-want-to-select');
        console.log(that);
    });
    

    我想上面的代码可以正确地选择我正在尝试选择的元素,但它不起作用。我做错什么了吗?因为我正在遍历的代码块是动态添加的,所以有没有不同的方法来选择它?

    4 回复  |  直到 8 年前
        1
  •  2
  •   Bhushan Kawadkar    8 年前

    尝试以下操作:您正在尝试获取最接近的div,然后查找不会给父div提供类的类 class-i... 你需要设置类选择器 .container 在里面 closest 只返回正确的父div,然后调用 find 就为了得到 class-i-want-to-select . 检查下面的代码

    $(document).on('click', '.remove', function () {
        var $parent = $(this).closest('div.container');
        var that = $parent.find('div.class-i-want-to-select');
        console.log(that);
    });
    
        2
  •  2
  •   Shilly    8 年前

    你的跨度也包在一个div里。所以closest将找到这个div,而不是带有类容器的div。而且那个div没有一个子类i-want-to-select。所以试着用 .closest( '.container' ) .

        3
  •  0
  •   Sujit Agarwal    8 年前

    试试这个-

    $('.remove').on('click', function () {
        var that = $(this).parent().parent().find('.class-i-want-to-select');
        console.log(that);
    });
    
        4
  •  0
  •   CPHPython    8 年前

    另一种方法是 parents() 而不是使用其中一个容器div作为其选择器:

    $('body').on('click', '.remove', function () {
        var that = $(this).parents('.container').find('.class-i-want-to-select');
        console.log(that.text());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
       <div>
          <span style="float:left;">some text</span>
          <span class="remove" style="float:right;">[X]</span> ///user clicks here
       </div>
       <div style="clear:both;"></div>
       <div class="class-i-want-to-select">I am the one you want!</div> ///want to select this element
    </div>