首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery与输出的文本交互

jQuery与输出的文本交互
EN

Stack Overflow用户
提问于 2018-12-29 04:05:54
回答 1查看 88关注 0票数 4

我有一个PHP应用程序,它输出PHP通知。这是在任何其他内容(包括DOCTYPE声明)之前,简单地发送到浏览器中的文本。

代码语言:javascript
复制
    <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上的内容?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-29 06:10:17

您可以使用$('body').contents()访问这些元素,因为浏览器将它们解释为主体的元素。当浏览器在doctype声明之前看到文本时,它会将文本和头部的内容转移到主体中,这是试图构建一个可行的DOM的方法,即使html无效。

由于浏览器已经重新组织了内容,所以您无法猜测头的第一个元素应该是什么。这个脚本允许您设置应该是head的第一个元素的元素。然后,脚本将访问您设置的元素之前的元素,并向您提供有关元素是文本节点还是DOM元素的信息。

您必须使用vanilla与文本节点交互,但其他节点可以使用jQuery。

代码语言:javascript
复制
// 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();
    }
});

代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53966612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档