如果<h1>
不存在,找到文档中的第一个标题标签(<h2>
到 <h6>
之一),如果标签文本等于标题文本,将元素更改为 <h1 class="heading1">
.
据我所知,这是可行的,但必须有一种更有效的方式来编写它。
var titleText = $('title').html()
var hOne = $('h1:eq(0)');
var hTwo = $('h2:eq(0)');
var hThree = $('h3:eq(0)');
var hFour = $('h4:eq(0)');
if (hOne.html() == titleText)
{
return;
}
else if (hTwo.html() == titleText)
{
var hTwoText = hTwo.html();
hTwo.replaceWith(function () {
return '<h1 class="heading1">' + hTwoText + "</h1>";
});
}
else if (hThree.html() == titleText)
{
var hThreeText = hThree.html();
hThree.replaceWith(function () {
return '<h1 class="heading1">' + hThreeText + "</h1>";
});
}
else if (hFour.html() == titleText)
{
var hFourText = hFour.html();
hFour.replaceWith(function () {
return '<h1 class="heading1">' + hFourText + "</h1>";
});
}
最佳答案
$(function () {
var title,
headerToReplace,
replacer;
if ( $('h1').length === 0 ) {
title = document.title;
headerToReplace = $(':header').filter(function () {
return $(this).text() === title;
});
if (headerToReplace.length) {
replacer = $('<h1 />', { 'class': 'heading1', text: 'title' });
headerToReplace.first().replaceWith(replacer);
}
}
});
关于javascript - 将文档中的第一个标题标签 (<h2>,<h3>..<h6>) 更改为 <h1>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866300/