使用jQuery访问父元素的第一个/最后一个子元素中的数据属性

我目前正在尝试实现令人耳目一新的帖子提要,并且正在进行如下操作,试图从子元素中获取data-pid:

HTML:

<div id="postFeed">
    <div data-pid="6">
        ...
    </div>
    ...
</div>

jQuery的:

$(document).ready(() => {
    alert($("#postFeed:first-child").attr("data-pid"));
    ...
});

我尝试了几种不同的方法,但是我得到的只是“未定义”。正确的方法是什么?

评论
Linda
Linda

Please understand that the :first-child selector selects all elements that are the first child of their parent. But here #postFeed is not the child you want to target, you want to target the div inside it. So, you just need to use :first-child selector on that child element like:

$(document).ready(() => {
  console.log($("#postFeed div:first-child").attr("data-pid"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="postFeed">
  <div data-pid="6">
    A
  </div>
  <div data-pid="8">
    B
  </div>
</div>
点赞
评论
也许
也许

当前脚本存在逻辑问题。

您应该使用的是-

$(document).ready(() => {
    alert($("#postFeed").children(":first").attr("data-pid"));
});

JS Fiddle

点赞
评论