简体   繁体   English

为什么此javascript在IE7或Safari中不起作用?

[英]Why would this javascript not work in IE7 or Safari?

Firefox handles it fine, but Safari and IE7 silently fail and do not insert the element. Firefox可以很好地处理它,但是Safari和IE7会静默失败,并且不会插入该元素。

<script type="text/javascript">
  var ul = document.getElementById('xg_navigation').getElementsByTagName('ul')[0];
  ul.innerHTML = '<li id="xg_tab_home" class="xg_subtab"><a href="http://somedomain.com/">Some Text</a></li>' + ul.innerHTML;
</script>

This is with an exisitng html structure like: 这是一个exisitng html结构,例如:

<div id="xg_navigation">
  <ul>
    <li><a href="...">Foo</a></li>
    ...
  </ul>
</div>

I dont have control over the HTML, but I do have the ability to insert a snippet of javascript in the page body. 我没有控制HTML的功能,但确实可以在页面正文中插入一小段javascript。

Sadly I appear to be poorly educated on cross browser javascript support. 不幸的是,我似乎对跨浏览器javascript支持的教育程度不高。 Do I need to hook it it up via an onPageLoad sort of event somehow? 我是否需要通过某种onPageLoad事件将其连接起来?

Seems like you are manipulating the DOM before it has been loaded, try adding that snippet of code inside the window.onload listener: 好像您在加载DOM之前就在对其进行操作,请尝试在window.onload监听器中添加该代码段:

<script type="text/javascript">
window.onload = function() {
    var ul = document.getElementById('xg_navigation').getElementsByTagName('ul')[0];
    ul.innerHTML = '<li id="xg_tab_home" class="xg_subtab"><a   href="http://somedomain.com/">Some Text</a></li>' + ul.innerHTML;
}
</script>

是的,在文档加载完成之前,IE无法访问DOM元素。

Usually you have to wait for the DOM to be ready to execute a script that modifies the DOM. 通常,您必须等待DOM准备就绪才能执行修改DOM的脚本。

An easy way to do that is to use jQuery : 一种简单的方法是使用jQuery

$(function() { 
    $('#xg_navigation ul').prepend('<li id="xg_tab_home" class="xg_subtab"><a href="http://somedomain.com/">Some Text</a></li>');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM