javascript 获取 <h1> 的内容将它们转换为文本并设置为页面的标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16949443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:34:32  来源:igfitidea点击:

Get contents of <h1> convert them it to text and set as a title of the page

javascriptjquery

提问by Ilja

I've got following structure of h1element

我有以下h1元素结构

<h1>
<a href="#">My Text</a> <span>More Text</span> another text <a href="#">and a bit more</a>
</h1>

How can I get contents from such h1and convert them to text so the output would be "My Text More Text another text and a bit more"

如何从中获取内容h1并将它们转换为文本,以便输出"My Text More Text another text and a bit more"

and after that place it into the <title>of the page? So no links, spans etc.. Just text?

然后将其放入<title>页面的 ?所以没有链接,跨度等。只是文本?

回答by j08691

With jQuery it's just:

使用 jQuery,它只是:

$('title').text($('h1').text());

回答by Ian

Without jQuery, you can access the <h1>'s textContentproperty (innerTextin old IE), and you can change document.title(like modifying the <title></title>). Here's an example:

如果没有 jQuery,您可以访问<h1>textContent属性(innerText在旧 IE 中),并且您可以更改document.title(例如修改<title></title>)。下面是一个例子:

var text = "textContent" in document.body ? "textContent" : "innerText";
document.title = document.getElementsByTagName("h1")[0][text];

Depending on how you want to target the <h1>, you can change the document.getElementsByTagName("h1")[0].

根据您希望如何定位<h1>,您可以更改document.getElementsByTagName("h1")[0].

Also, I'm not sure how it affects the title, but the whitespace before the first <a>and after the last </a>will be included unless you trimthe string. So maybe turn it into:

另外,我不确定它如何影响title,但是除非您使用字符串,否则将包含第一个之前<a>和最后一个之后的空格。所以也许把它变成:</a>trim

function trim(s) {
    if (typeof s === "string") {
        s = s.replace(/^\s+|\s+$/g, "");
    }
    return s;
}

var el = document.getElementsByTagName("h1")[0],
    text = "textContent" in el ? "textContent" : "innerText";
document.title = trim(el[text]);

DEMO:http://jsfiddle.net/tzGzC/

演示:http : //jsfiddle.net/tzGzC/

Of course, with just jQuery, it's a lot simpler:

当然,只用 jQuery,就简单多了:

var el = $("h1").eq(0),
    text = el.text();
document.title = $.trim(text);

DEMO:http://jsfiddle.net/kMXLW/

演示:http : //jsfiddle.net/kMXLW/

References:

参考:

回答by This Guy

var h1content = document.getElementById("h1").innerHTML;
// stripped string taken from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
var newTitle = h1content.replace(/(<([^>]+)>)/ig,"");
document.title = newTitle;

Something to note, crawlers do NOT follow Javascript code, meaning that although this will change the title of the page, it will not be Search Engine Optimized.

需要注意的是,爬虫不遵循 Javascript 代码,这意味着虽然这会改变页面的标题,但它不会被搜索引擎优化。