使用Javascript访问<noscript>的内容

mac*_*osh 19 javascript innerhtml noscript

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

<script type="text/javascript"> alert($('example').innerHTML);</script>
Run Code Online (Sandbox Code Playgroud)

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

ps我在这个特定项目上使用原型.

Sho*_*og9 15

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 用jQuery尝试$($("noscript").text()). (2认同)

kin*_*rey 5

我不确定原型,但这在带有 jQ​​uery 的 Chrome 中有效:

$('noscript').before($('noscript').text());
Run Code Online (Sandbox Code Playgroud)