应该得到 child 但不知何故得到 parent ID

Supposed to get the child but somehow gets the parent ID

美好的一天。我有一个代码。据我了解,clicked2 应该获得 ID "Third",因为它正在寻找 children。但不知何故,它总是得到 id "First"。我如何获得 "Third"?

<!DOCTYPE html>
<html>
<body>

    <div class="menu" id="First">
       <button id="Second">eee</button>
       <button id="Third">yyy</button>
    </div>
    <div class="holder"></div>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

          $(document).on('click', '.menu', function(e) {
               var clicked = e.target.id || this.id;
               var clicked2 = e.target.children.id || this.id;
               var y = clicked2.replace(/\D/g, '');
               var x = clicked.replace(/\D/g, '');
               var w = 0;

               $('.holder') .append('<BR>'+clicked+'<BR>'+clicked2);

               });

   </script>

</body>
</html>

添加这个var clicked2 = $(this).children("button").next().attr("id") 它将 return 第二个按钮的 ID。

试试这个

$(document).on('click', '.menu', function(e) {
var clicked = e.target.id || this.id;
var clicked2 = $(this).children("button").next().attr("id") || this.id;


var y = clicked2.replace(/\D/g, '');
var x = clicked.replace(/\D/g, '');
var w = 0;

$('.holder') .append('<BR>'+clicked+'<BR>'+clicked2);

   });

Demo Here

children() returns 所有孩子的,所以你需要解决正确的问题:

var clicked2 = $(this).children().next().attr("id");