<noscript><div id="example">I want to get this innerHTML</div></noscript>
<script type="text/javascript"> alert($('example').innerHTML);</script>
这个Javascript片段只返回一个空字符串。有没有一种方法可以获取noscript节点的内容?
附注:我在这个项目中使用Prototype。
<noscript><div id="example">I want to get this innerHTML</div></noscript>
<script type="text/javascript"> alert($('example').innerHTML);</script>
这个Javascript片段只返回一个空字符串。有没有一种方法可以获取noscript节点的内容?
附注:我在这个项目中使用Prototype。
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内容似乎得到了更好的支持,但我仍然认为这是一个边缘案例,可能比其他元素更容易出现错误——如果您有其他选择,我建议避免使用它。noscript
标签的内容,从而使其内部内容为空?如果是真的,这似乎有点奇怪。我今天正在尝试实现类似的东西,但这让我想知道noscript
规范是否没有详细说明如何处理其内容。 - Super Cat我不确定 prototype 是否也适用,但是这个方法可以在 Chrome 中和 jQuery 一起使用:
$('noscript').before($('noscript').text());
来自HTML 4.0规范:
NOSCRIPT元素允许作者在脚本未执行时提供替代内容。 NOSCRIPT元素的内容只应在以下情况下由支持脚本的用户代理呈现:
- 用户代理被配置为不评估脚本。
- 用户代理不支持文档中早期SCRIPT元素调用的脚本语言。
我认为这意味着,如果浏览器启用了脚本,则忽略NOSCRIPT标记(在本例中为div)的全部内容。您是否验证了“示例”div在您的情况下是否可以通过DOM访问?