如何使用 jQuery.closest() 方法選擇類名?
closest() 方法會從當前元素開始返回第一個匹配傳遞表示式的祖先元素。返回的 jQuery 物件只有一個或零個元素。使用類選擇器很簡單,下面我們就來看看如何使用它。
程式碼示例
你可以嘗試執行以下程式碼片段,瞭解如何使用 jQuery.closest() 方法查詢類選擇器
<!DOCTYPE html> <html> <head> <style> .myclass * { display: block; border: 2px solid blue; color: red; padding: 5px; margin:10px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("span").closest(".one").css({"color": "maroon", "border": "5px solid maroon"}); }); </script> </head> <body class="myclass">body <div style="width:500px;">div <ol>ol - This is the third ancestor <ol>ol - This is the second ancestor <li>li - This is the direct parent element <span>demo</span> <span class="one">demo - using class selector with closest() method</span> </li> </ol> </ol> </div> </body>
廣告