我有一个PHP应用程序,它输出PHP通知。这是在任何其他内容(包括DOCTYPE声明)之前,简单地发送到浏览器中的文本。
<br />
<b>Notice</b>: Undefined property: bla bla blap</b> on line <b>16</b><br />
<!DOCTYPE html>
...regular web page有没有一种使用jQuery与文本交互的方法?它在浏览器中显示为第一件事。如何在<!DOCTYPE html>中选择jQuery上的内容?
发布于 2018-12-29 06:10:17
您可以使用$('body').contents()访问这些元素,因为浏览器将它们解释为主体的元素。当浏览器在doctype声明之前看到文本时,它会将文本和头部的内容转移到主体中,这是试图构建一个可行的DOM的方法,即使html无效。
由于浏览器已经重新组织了内容,所以您无法猜测头的第一个元素应该是什么。这个脚本允许您设置应该是head的第一个元素的元素。然后,脚本将访问您设置的元素之前的元素,并向您提供有关元素是文本节点还是DOM元素的信息。
您必须使用vanilla与文本节点交互,但其他节点可以使用jQuery。
// the script needs to know what should have been the first element in the head
const firstElementInHead = $( 'title' );
// remove all nodes prior to the intended content
$('body').contents().each( function() {
if ( $(this).index() < firstElementInHead.index() ) {
$(this).remove();
}
});
<br />
<b>Notice</b>: Undefined property: bla bla blap on line <b>16</b><br />
<!doctype html>
<html lang="en">
<head>
<title>The Broken Page</title>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
// the script needs to know what should have been the first element in the head
const firstElementInHead = $('title');
// log the nodes that apear prior to the intended content
$('body').contents().each(function() {
if ($(this).index() < firstElementInHead.index()) {
if (this.nodeType == Node.TEXT_NODE) {
console.log('This is a text node. You can change it by setting this.nodeValue, remove it by calling this.remove(), or other vanilla JS operations.');
console.log(this);
} else {
console.log('This is a DOM element. You can interact with it using jQuery the same way you interact with any normal DOM element.');
console.log(this);
}
}
});
</script>
</head>
<body style="padding:0; margin:0;">
<p style="padding:0; margin:0; background:red;">Test</p>
</body>
</html>
https://stackoverflow.com/questions/53966612
复制相似问题