首页 > 解决方案 > 在 Jquery 中创建父/子结构时寻求帮助

问题描述

我有以下 HTML:

<p>{{ $comment->comment }}</p>单击“编辑”按钮后,我正在尝试将其发送到 Jquery 函数。我需要帮助来完成以下结构:

Comment = event.target.parentNode.childNodes[1];

<div class=" p-3 border-top border-bottom bg-light">
  <div class="d-flex align-items-center osahan-post-header">
    <div class="dropdown-list-image mr-3 mb-auto"><img class="rounded-circle" src="img/p8.png" alt=""></div>
    <div class="mr-1">
      <div class="text-truncate h6 mb-3">{{ $comment->user->first_name }} {{ $comment->user->last_name }}</div>
      <p>{{ $comment->comment }}</p>
    </div>
    <span class="ml-auto mb-auto">
      <div class="text-right text-muted pt-1 small">{{ $comment->created_at}}</div>
    </span>
  </div>
  <div class="post" align="right" data-postid="{{ $comment->id }}">
    <a href="#" data-toggle="modal" id="eid">Edit</a>
  </div>
</div>
</div>

标签: javascriptjquery

解决方案


如果您要修复无效的 HTML(正如评论中已经提到的, a<div>不能在 a 中<span>),您可以获得如下评论:

document.getElementById("eid").onclick = function(e) {
  let comment = e.target.closest(".p-3").getElementsByTagName("p")[0].innerHTML;
  console.log(comment);
};

或者,如果您使用 jQuery:

 $("#eid").on("click", function(){
    let comment = $(this).closest(".p-3").find("p").text();
    console.log(comment);
 });

推荐阅读