首页 > 解决方案 > 使用“this”jquery 获取父母文本数据

问题描述

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

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

我需要获取info__meta-dates文本,所以只有使用onClickjQuery 中的事件的日期,这是我到目前为止的代码:

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

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

标签: javascriptjquerytextonclickparent

解决方案


您可以clone跨标签并使用从克隆元素中.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>


推荐阅读