如何在 jQuery 中找到所有點選元素的同級元素?


要在 jQuery 中找到所有點選元素的同級元素,請使用父級和同級方法,並選擇類來找到所有同級元素。

示例

你可以嘗試執行以下程式碼以在 jQuery 中找到所有點選元素的同級元素

線上演示

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".target").click(function(){
     $(this).parent().siblings().removeClass("selectedClass");
     $(this).parent().addClass("selectedClass");
  });
});
</script>
<style>
  a {
      cursor:pointer;
    }
  .selectedClass{
      color:blue;
    }
</style>
</head>
<body>
<h1>Countries</h1>
<ul>
    <li><a class="target">India</a></li>
    <li><a class="target">US</a></li>
    <li><a class="target">UK</a></li>
</ul>
</body>
</html>

更新於: 2019 年 12 月 17 日

632 次瀏覽

開啟你的 事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.