【问题标题】:Select parent DIV contents based on a containing class using jquery使用 jquery 基于包含类选择父 DIV 内容
【发布时间】:2019-05-04 13:08:30
【问题描述】:

例如,我想根据 DIV 中的类抓取 DIV 的内容,我的页面将包含

<html>
  <head></head>
  <body>
    <div>
      <p class="foo">some text</p>
      <p>test1</p>
      <p>test 2</p>
    </div>
  </body>
</html>

结果是:

<div>
  <p class="foo">some text</p>
  <p>test1</p>
  <p>test 2</p>
</div>

我试过了

$.get("https://some.url.com/index.html", function(my_var) {
  console.log($(my_var).closest('div').find('.foo'));  
});

但是只得到一个空结果?

【问题讨论】:

    标签: javascript jquery html jquery-selectors


    【解决方案1】:

    您应该首先找到.foo,然后使用.closest() 选择它的父项

    $.get("https://some.url.com/index.html", function(my_var) {
      console.log($(my_var).find(".foo").closest('div'));  
    });
    

    $(".foo").closest("div").css("color", "red");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <html>
      <head>
      </head>
      <body>
        body
        <div>
          <p class="foo">some text</p>
          <p>test1</p>
          <p>test 2</p>
        </div>
        body
      </body>
    </html>

    【讨论】:

      【解决方案2】:

      为了更好的方法需要首先定位body而不是找到您的特定类find('.foo'),您可以查看如下工作示例:

      $(document).ready(function(){
      
      $('body').closest('body').find('.foo').css("color", "red")
      
      })
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
      <html>
        <head>
        </head>
        <body>
          <div>
            <p class="foo">some text</p>
            <p>test1</p>
            <p>test 2</p>
          </div>
        </body>
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-09
        相关资源
        最近更新 更多