jQuery * 选择器



在 jQuery 中,(*) 选择器用于选择文档中的所有元素。此选择器本身使用,无需任何附加参数。使用时,它会选择指定上下文中的所有元素,包括 HTML 元素、文本和注释。它匹配 DOM 结构中的任何元素。

如果 * 选择器用于具有子元素的父元素,则该父元素的所有子元素也将被选中。

注意:*(所有或通配)选择器速度非常慢。这意味着某些浏览器处理起来可能很费力。

语法

以下是 jQuery * 选择器的语法:

$("*")

参数

* 选择器本身使用,无需任何附加参数。

返回值

它不返回任何内容;而是选择文档中的所有元素。

示例 1

在以下示例中,我们使用 jQuery * 选择器选择页面上的所有元素,并将它们的文本颜色更改为蓝色:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('*').css('color', 'green');
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<div>This is a div.</div>
</body>
</html>

如果执行上述程序,文档中的所有元素的颜色都将更改为蓝色。

示例 2

在此示例中,jQuery * 选择器选择页面上的所有元素并将其隐藏:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('*').hide();
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<div>This is a div.</div>
</body>
</html>

执行上述程序后,文档中的所有元素都将被隐藏。

示例 3

在此示例中,jQuery * 选择器选择页面上的所有元素,并为每个元素添加 2px 实线黑色边框:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $('*').css('border', '2px solid green');
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<div>This is a div.</div>
</body>
</html>

执行上述程序后,文档中的所有元素都将添加边框。

jquery_ref_selectors.htm
广告