【问题标题】:Can you retrieve the value from an attribute as it appeared in the source?您可以从源中出现的属性中检索值吗?
【发布时间】:2018-11-22 20:18:09
【问题描述】:

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&amp;#32;section" 而不是 "The section"

【问题讨论】:

  • 这只能在通过异步 GET 请求获得的 HTML 上使用字符串解析来完成。显然 DOM API 无法访问不在 DOM 中的元素,而一旦元素在 DOM 中,它显然已经被解析了。
  • 啊,是的,我不想那样做。充其量是再次下载相同的 HTML 文件并不得不搜索它;在最坏的情况下,重新调用网络应用程序,谁知道有什么副作用。不,不。

标签: javascript html dom


【解决方案1】:

没有办法像源代码一样在浏览器中获取已解析的 Unicode 字符 HTML 文件,因为 &amp;#32; 是一个空格,所以我们可以使用这个解决方法来处理任何标题之间有空格的单词。

<section id="theSection" title="The&#32;section">The section</section>

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

我知道这是愚蠢的答案, 但如果真的打算处理空间 unicode,则使用 fetch(url) 访问具有此 &lt;section id="theSection" title="The&amp;#32;section"&gt;The section&lt;/section&gt; 的 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 源代码中处理的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多