【问题标题】:Get parents text data using "this" jquery使用“this”jquery 获取父母文本数据
【发布时间】:2020-11-24 14:35:47
【问题描述】:

我的文档 HTML STRUCTURE 中有以下 HTML 结构

[![在此处输入图片描述][1]][1]

我需要获取 info__meta-dates 文本,所以只有在 jQuery 中使用 onClick 事件的日期,这是我目前拥有的代码:

 $("input[type=checkbox]").click(function (e) {
       
            $(this)
                .parent()
                .parent()
                .parent()
                .find(".info__meta--dates")
                .text()
         );
});

但我也得到了嵌套范围内的 date 文本。

【问题讨论】:

  • 嗨,你试过下面的代码吗?
  • @Swati 嗨,是的,它完美无缺!刚刚将您的解决方案添加为一个:)

标签: javascript jquery text onclick parent


【解决方案1】:

你可以clone那个span标签并使用.remove()从克隆的元素中删除mdc-typography--caption,这样最终的结果就是你需要的文本

演示代码

$("input[type=checkbox]").click(function(e) {
  var texts = $(this).closest(".ev-info_meta").find(".info__meta--dates").clone(); //clone that span tag
  texts.find('span.mdc-typography--caption').remove(); //remove elemnt with class mdc-typography--caption
  console.log(texts.text().trim()); //show 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ev-info_meta">
  <span class="info__meta--dates"><span class="mdc-typography--caption">dates</span> fffff</span>
  <div>
    <input type="checkbox">
  </div>
</div>

【讨论】:

    【解决方案2】:

    由于没有直接获取日期的元素,您可以尝试上述 Swati 解释的方法,如果您不愿意从 DOM 中删除元素,请尝试使用字符串操作方法。

    以下方法仅适用于这种情况。

    $("input[type=checkbox]").click(function (e) {
           
             let dateString =  $(this).parent()
                    .parent()
                    .parent()
                    .find(".info__meta--dates")
                    .text()
             );
           //removing the "date" string from the entire string
           let date = dateString.substring(4,dateString.length).trim();
           console.log(date);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2016-01-04
      • 1970-01-01
      • 2011-12-25
      相关资源
      最近更新 更多