本文介绍了访问< noscript>的内容用Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<noscript><div id="example">I want to get this innerHTML</div></noscript>

<script type="text/javascript"> alert($('example').innerHTML);</script>

这个javascript片段只返回一个空字符串。有没有办法获取noscript节点的内容?

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s。我正在使用这个特定项目的原型。

p.s. I'm using prototype on this particular project.

推荐答案

如果启用了脚本, - 尽管它必须是可解析的 text,对内容有一些限制。考虑到这一点,您应该能够提取文本,解析它,然后找到您想要的元素。以下是一个基本的例子:

If scripting is enabled, the noscript element is defined as containing only text - though it must be parsable text, with some restrictions on content. With that in mind, you should be able to extract the text, parse it, and then find your desired element. A rudimentary example of this follows:

var nos = document.getElementsByTagName("noscript")[0]; 
// in some browsers, contents of noscript hang around in one form or another
var nosHtml = nos.textContent||nos.innerHTML; 

if ( nosHtml )
{
  var temp = document.createElement("div");
  temp.innerHTML = nosHtml;

  // lazy man's query library: add it, find it, remove it
  document.body.appendChild(temp);
  var ex = document.getElementById("example");
  document.body.removeChild(temp);

  alert(ex.innerHTML);
}

请注意,当我最初撰写此答案时,上述操作在Google Chrome中失败;这些天对noscript内容的访问似乎有点得到了更好的支持,但它仍然让我感到极为震撼,因为它可能比其他元素更容易出现错误 - 如果你有其他选择,我会避免它。

Note that when I originally wrote this answer, the above failed in Google Chrome; access to noscript content appears to be somewhat better-supported these days, but it still strikes me as an edge-case that is perhaps somewhat more likely than other elements to exhibit bugs - I would avoid it if you've other options.

这篇关于访问&lt; noscript&gt;的内容用Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:41