如何用jQuery给文本的所有单词加下划线
给出一个声明,任务是用jQuery给HTML页面的所有文字加下划线。我们将使用text-decoration属性来给每个单词添加下划线。
HTML code:
<!DOCTYPE html>
<html>
<head>
<style>
p span {
text-decoration: underline;
}
</style>
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<h2>GeeksForGeeks</h2>
<h2>
How to underline all the words
of a text using jQuery?
</h2>
<p>
Geeks For Geeks. A computer
science portal for Geeks.
</p>
</body>
</html>
jQuery 代码:
$('p').each(function () {
var text_words = $(this).text().split(' ');
$(this).empty().html(function () {
for (i = 0; i < text_words.length; i++) {
if (i === 0) {
$(this).append('<span>'
+ text_words[i] + '</span>');
} else {
$(this).append(' <span>'
+ text_words[i] + '</span>');
}
}
});
});
最终代码:以下代码是上述两个代码片断的组合。
<!DOCTYPE html>
<html>
<head>
<style>
p span {
text-decoration: underline;
}
</style>
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<h2>GeeksForGeeks</h2>
<h2>
How to underline all the words
of a text using jQuery?
</h2>
<p>
Geeks For Geeks. A computer
science portal for Geeks.
</p>
<script>
(document).ready(function () {
('p').each(function () {
var text_words =
(this).text().split(' ');
(this).empty().html(function () {
for (i = 0; i < text_words.length; i++) {
if (i === 0) {
(this).append('<span>'
+ text_words[i] + '</span>');
}
else {
(this).append(' <span>'
+ text_words[i] + '</span>');
}
}
});
});
});
</script>
</body>
</html>
输出:
支持的浏览器列举如下:
- Google Chrome
- Internet Explorer
- Firefox
- Opera
- Safari