suchen
  • Anmelden
  • Melden Sie sich an
Passwort-Reset erfolgreich

Verfolgen Sie die Projekte, die Sie interessieren, und erfahren Sie die neuesten Nachrichten über sie

jQuery 选择器

jQuery 选择器

jQuery 选择器允许您对 HTML 元素组或单个元素进行操作。

jQuery 选择器

jQuery 选择器允许您对 HTML 元素组或单个元素进行操作。

jQuery 选择器基于元素的 id、类、类型、属性、属性值等"查找"(或选择)HTML 元素。 它基于已经存在的 CSS 选择器,除此之外,它还有一些自定义的选择器。

jQuery 中所有选择器都以美元符号开头:$()。

元素选择器

jQuery 元素选择器基于元素名选取元素。

在页面中选取所有 <p> 元素:

$("p")

实例

用户点击按钮后,所有 <p> 元素都隐藏:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>jQuery示例</title> 
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>
<body>
<h2>这是一个标题</h2>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>点我</button>
</body>
</html>

#id 选择器

jQuery #id 选择器通过 HTML 元素的 id 属性选取指定的元素。

页面中元素的 id 应该是唯一的,所以您要在页面中选取唯一的元素需要通过 #id 选择器。

通过 id 选取元素语法如下:

$("#test")

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#test").hide();
  });
});
</script>
</head>
<body>
<h2>好好学习</h2>
<p>天天向上</p>
<p id="test">PHP测试</p>
<button>点我</button>
</body>
</html>

.class 选择器

jQuery 类选择器可以通过指定的 class 查找元素。

语法如下:

$(".test")

语法                                          描述

$("*")                                 选取所有元素       

$(this)                         选取当前 HTML 元素        

$("p.intro")          选取 class 为 intro 的 <p> 元素        

$("p:first")                 选取第一个 <p> 元素        

$("ul li:first")    选取第一个 <ul> 元素的第一个 <li> 元素        

$("ul li:first-child")    选取每个 <ul> 元素的第一个 <li> 元素     

$("[href]")                选取带有 href 属性的元素        

$("a[target='_blank']")    选取所有 target 属性值等于 "_blank" 的 <a> 元素        

$("a[target!='_blank']")    选取所有 target 属性值不等于 "_blank" 的 <a> 元素        

$(":button")    选取所有 type="button" 的 <input> 元素 和 <button> 元素       

$("tr:even")                   选取偶数位置的 <tr> 元素        

$("tr:odd")                    选取奇数位置的 <tr> 元素    

独立文件中使用 jQuery 函数

如果您的网站包含许多页面,并且您希望您的 jQuery 函数易于维护,那么请把您的 jQuery 函数放到独立的 .js 文件中。

当我们在教程中演示 jQuery 时,会将函数直接添加到 <head> 部分中。不过,把它们放到一个单独的文件中会更好,就像这样(通过 src 属性来引用文件):

<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script src="my_jquery_functions.js"></script>
</head>


neue Datei
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $(".test").hide(); }); }); </script> </head> <body> <h2 class="test">你马上就看不见我了</h2> <p class="test">你就要看不见我了</p> <p>为什么还能看见我</p> <button>点我</button> </body> </html>
Code zurücksetzen
Automatische Operation
einreichen
Vorschau Clear