如何在 jQuery 中獲取 $(this) 選擇器的子級?


如需獲取 $(this) 選擇器的子級,請使用 jQuery find() 方法。你可以嘗試執行以下程式碼來獲取 $(this) 選擇器的子級 −

示例

即時演示

<html>
<head>
  <title>jQuery Example</title>
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    $('#mydiv').click(function(){
      alert($(this).find('img:last-child').attr('src'));
   });
  });
</script>
<style>
  #my_div {
   width: 200px;
   height: 200px;
   background-color: red;
  }
</style>
</head>

<body>
<div id='mydiv'>
  <img src='https://tutorialspoint.tw/videotutorials/images/tutorial_library_home.jpg' width='200' height='200' alt='Tutorials Library'>
  <img src='https://tutorialspoint.tw/videotutorials/images/tutor_connect_home.jpg' width='200' height='200' alt='Video Tutorials'>
</div>
</body>
</html>

更新於: 2020 年 6 月 20 日

102 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.