如何使用jQuery找到页面中第一个被强调的元素的标题属性
在JavaScript中,我们有很多不同的库,用于不同的目的。jQuery也是JavaScript库的一部分,它是为了简化JavaScript代码而制作的,你可以做动画,使你的网站更有创意以及动态。
在学习jQuery库之前,你必须有HTML、CSS和JavaScript的基本知识。
在这篇文章中,我们将看到如何使用jQuery找到页面上第一个强调的标题属性。title是一个属性,而不是一个元素,是head元素的一部分。Emphasized是一个元素,用来赋予该文本更多的重要性。
使用的方法/功能 –
- .click() 。当发生点击事件时,该方法会触发click事件的运行。
- .attr() 。它是用来获取匹配元素集合中第一个元素的属性值的。
- .text()。它用于获取匹配元素集合中每个元素的组合文本内容,包括它们的后代。
例子1:在下面的例子中,首先,我们将找到emphasized元素并在点击按钮后打印标题值。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<style type="text/css">
button {
display: block;
margin: 20px 0 0 0;
}
</style>
</head>
<body>
<p>
GeeksForGeeks
<em title="is a computer science portal for geeks.">
(GFG)
</em>.
</p>
<p id="id1"></p>
<button id="button1">
Click to see what is there in the title attribute
</button>
<script>
("#button1").click(function () {
var title =("em").attr("title");
$("#id1").text(title);
});
</script>
</body>
</html>
输出:段中的文字和强调元素被显示出来,然后是按钮。点击按钮后,你可以看到title属性中的文本(值)。
示例 2:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<style type="text/css">
button {
display: block;
margin: 20px 0 0 0;
}
</style>
</head>
<body>
<p>John <em title="You Can't see me">Cena</em>.</p>
<p id="id1"></p>
<button id="button1">
Click to see what is there in the title attribute
</button>
<script>
("#button1").click(function () {
var title =("em").attr("title");
$("#id1").text(title);
});
</script>
</body>
</html>
输出:
Before click: