如何使用jQuery获得当前HTML页面的标题
假设你给了一个HTML页面,任务是只用jQuery的帮助来获得HTML页面的标题。有两种方法,将在下面讨论。
方法1:$(‘title’)jQuery选择器用于选择文档的标题元素,我们可以使用选择器上的text()方法来获得文档的标题。
- 示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
Get title of current HTML page
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
body {
text-align:center;
}
#gfg{
color: green;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<b>
Click on button to get HTML document's title
</b>
<br><br>
<button onClick="GFG_Fun()"> click here</button>
<p id="gfg">
</p>
<script>
var down = document.getElementById('gfg');
// Main function
function GFG_Fun() {
down.innerHTML = $('title').text();
}
</script>
</body>
</html>
- 输出:
方法2:$(document) jQuery选择器用于选择HTML文档,我们可以使用选择器上的attr()方法通过传递’title’作为参数来获得文档的标题。
- 示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
Get title of current HTML page
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
body {
text-align:center;
}
#gfg{
color: green;
font-size: 24px;
font-weight: bold;
}
</style>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<b>
Click on button to get HTML document's title
</b>
<br><br>
<button onClick="GFG_Fun()"> click here</button>
<p id="gfg">
</p>
<script>
var down = document.getElementById('gfg');
// Main function
function GFG_Fun() {
down.innerHTML = $(document).attr('title');
}
</script>
</body>
</html>
- 输出: