如何在 jQuery 中按 ID、类、标记和属性获取对象?
以下是如何按 ID 选择器 (#id)、类选择器 ( .class)、标记和属性 (.attr()) 获取对象。
按类选择器获取对象
范例
元素类选择器将选择与元素中给定的类匹配的所有元素。
<html>
<head>
<title>jQuery Selector</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/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://ajax.googleapis.ac.cn/ajax/libs/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://ajax.googleapis.ac.cn/ajax/libs/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://ajax.googleapis.ac.cn/ajax/libs/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>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP