代码之家  ›  专栏  ›  技术社区  ›  Mr Lister hawi

您能否从源中显示的属性中检索该值?

  •  2
  • Mr Lister hawi  · 技术社区  · 6 年前

    评论 this question 让我好奇。

    在JavaScript中,是否可以获取HTML属性的“原始”值,即解析前在源代码中写入的方式?

    假设您有以下HTML:

    <section id="theSection" title="The&#32;section">The section</section>
    
    <script>
     console.log(document.getElementById('theSection').title);
    </script>
     

    我需要在脚本中编写什么才能使其输出标题的原始转义值,而不是解析后的值?
    JavaScript节点有很多属性和值,但在本例中,没有一个 "The&#32;section" 而不是 "The section"

    1 回复  |  直到 6 年前
        1
  •  0
  •   Poode    6 年前

    无法在类似浏览器的源代码中获取已解析的Unicode字符 HTML文件和as &#32; 是一个空格,那么我们可以使用此变通方法,因为任何标题的单词之间都有空格。

    <section id="theSection" title="The&#32;section">The section</section>
    
    <script>
     console.log(document.getElementById('theSection').title.split(' ').join('&#32;'));
    </script>
     

    我知道这是愚蠢的回答, 但是,如果真的打算处理空间unicode,那么点击包含以下内容的url <section id="theSection" title="The&#32;section">The section</section> 具有 fetch(url) 如下所示:

    fetch('stackoverflow.com')
      .then(async (res) => {
        const text = await res.text();
       // process the text with any unicode charachter as it is now 100% string 
      }
    );
    

    现在,源HTML文件是一个字符串。在您的示例中,最好将字符串上的javascript与正则表达式一起使用,以查找您希望在html源代码中处理的内容。