具有屬性選擇器 [name]


attributeHas 選擇器

說明: 選取具有指定屬性(任何值)的元素。

  • 新增版本: 1.0jQuery( "[attribute]" )

    屬性: 屬性名稱。

範例

將單一點擊事件繫結至具有 ID 的 div,並將 ID 新增至 div 的文字中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>attributeHas demo</title>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>nope</div>
<script>
// Using .one() so the handler is executed at most once
// per element per event type
$( "div[id]" ).one( "click", function() {
var idString = $( this ).text() + " = " + $( this ).attr( "id" );
$( this ).text( idString );
});
</script>
</body>
</html>

示範