选择第一个孩子的元素

时间:2019-04-13 20:56:24

标签: javascript jquery html

我有一个看起来像这样的函数:

$(".container").on("click", ".comment:first-child > .like_btn", function () {
    console.log("it works!");
});

.comment中的.container被动态添加。我想做的是检测是否单击了第一个评论的“赞”按钮。但是,我现在所拥有的不起作用。我究竟做错了什么?

HTML

<div class="container">
  <div class="comment"> //Dynamically added
     <div class="like_btn"></div>
  </div>
</div>

编辑:没有错误,只是click事件不会触发。

4 个答案:

答案 0 :(得分:3)

尝试将处理程序附加到document

$(document).on("click", ".container .comment:first-child > .like_btn", function() {
    console.log("it works!");
});

setTimeout(() => $(".comment").append("<div class='like_btn'>Like!</div>"), 2000);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="container">
  <div class="comment"> //Dynamically added
  </div>
</div>

答案 1 :(得分:2)

一种解决方案是在document元素上使用事件委托,如下所示:

$(document).ready(function()
{
    $(".container").append(
      `<div class="comment">
         <div class="like_btn">LIKE 1</div>
       </div>
       <div class="comment">
         <div class="like_btn">LIKE 2</div>
       </div>`
    );
});

$(document).on("click", ".container .comment:first-child > .like_btn", function()
{
    console.log("it works!");
});
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
</div>

但是,如果也未动态添加.container元素,则您的代码应该可以正常工作,如以下示例所示:

$(document).ready(function()
{
    $(".container").append(
      `<div class="comment">
         <div class="like_btn">LIKE 1</div>
       </div>
       <div class="comment">
         <div class="like_btn">LIKE 2</div>
       </div>`
    );
});

$(".container").on("click", ".comment:first-child > .like_btn", function()
{
    console.log("it works!");
});
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
</div>

答案 2 :(得分:0)

$(document).ready(function()
{
    $(".container").append(
      `<div class="comment">
         <div class="like_btn">LIKE 1</div>
       </div>
       <div class="comment">
         <div class="like_btn">LIKE 2</div>
       </div>`
    );
});

$(document).on("click", ".container div:first-of-type > .like_btn", function()
{
    console.log("it works!");
});
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
</div>

答案 3 :(得分:-1)

尝试删除'>'

$('.container .comment .like-btn').on('click', function(){ //do something })