jQuery查找当前DOM之外的元素不起作用

jQuery to find element outside of current DOM not working

本文关键字:元素 不起作用 DOM 查找 jQuery      更新时间:2023-09-26

我正在构建一个注释系统的原型。因为会有多个帖子可以评论。我正在通过在点击"发送评论"按钮时插入文本来测试这一点。单击此按钮时,它应该搜索父级以找到空注释

,并将其附加为占位符文本,但它什么也没做。

HTML

<form class="comment-box">
    <textarea placeholder="Enter your comment here"></textarea>
    <span class="brand-color">0/400</span>
    <a class="btn submit-comment">Send comment</a>
</form>
<p class="empty-comment">
</p>

jQuery

$('.submit-comment').click(function() {
    event.preventDefault();
    $(this).parent().find('.empty-comment').append('comment inserted');
});

JSFiddle

this不是字符串,.empty-comment也是父级的下一个同级。

$('.submit-comment').click(function(event) {
  event.preventDefault();
  $(this).parent().next('.empty-comment').append('comment inserted');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="comment-box hide">
  <textarea placeholder="Enter your comment here"></textarea>
  <span class="brand-color">0/400</span>
  <a class="btn right submit-comment">Send comment</a>
</form>
<p class="empty-comment">
</p>