这是通过ID选择器(#id),类选择器(.class),标签和属性(.attr())获取对象的方法。
通过类选择器获取对象
元素类选择器选择与给定元素类匹配的所有元素。
<html> <head> <title>jQuery Selector</title> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".big").css("background-color", "yellow"); }); </script> </head> <body> <div class = "big" id="div1"> <p>This is first division of the DOM.</p> </div> <div class = "medium" id = "div2"> <p>This is second division of the DOM.</p> </div> </body> </html>
通过ID选择器获取对象
元素ID选择器选择具有给定id属性的单个元素:
<html> <head> <title>jQuery Selector</title> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $(function(){ $("#submit").click(function(){ alert($('input:radio:checked').val()); }); }); </script> </head> <body> <form id="myForm"> Select a number:<br> <input type="radio" name="q1" value="1">1 <input type="radio" name="q1" value="2">2 <input type="radio" name="q1" value="3">3<br> <button id="submit">Result</button> </form> </body> </html>
通过标签获取对象
为此,在下面传递特定标签的名称,即<a>标签:
<html> <head> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a").click(function(){ $("a.active").removeClass("active"); $(this).addClass("active"); }); }); </script> <style> .active { font-size: 22px; } </style> </head> <body> <a href="#" class="">One</a> <a href="#" class="">Two</a> <p>Click any of the link above and you can see the changes.</p> </body> </html>
按属性获取对象
使用.attr(),您可以获取任何标签的任何属性。这是显示如何获取属性值的示例:
<html> <head> <title>jQuery Example</title> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("img").attr("height", "200"); }); }); </script> </head> <body> <img src="/green/images/logo.png" alt="logo" width="450" height="160"><br> <button>Change the height</button> </body> </html>