我的Javascript函数受已定义的另一个JS函数的影响 [英] My Javascript function is influenced by another JS function already defined

查看:103
本文介绍了我的Javascript函数受已定义的另一个JS函数的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有HTML / CSS / JS页面,在< head> 标签中定义了CSS和JS函数(不是由自己创建)。页面在开头显示标题,下面有四个由CSS样式定义的选项卡,使用JS动态地工作。然后我想添加我自己的JS函数,它应该加载 onload

 < script type =text / javascript> 
function replaceSrc()
{
document.getElementById(ytplayer)。src =blablabla;
}
window.onload = replaceSrc;
< / script>

但是,当运行页面时,CSS / JS生成的所有内容都会消失



所以我的问题是:


  1. 可能是问题已经有一个定义的JS函数正在加载 onload

  2. 如果是这样,如何处理呢?

我已经尝试将函数声明放入HTML中的不同位置,从标签中删除并放入标签,但仍然不会工作。

解决方案

当你(或别人的)使用window.onload = someFunction时,你删除所有先前加载的加载事件处理程序。 p>

您应该使用 addEventListener < a>:

  window.addEventListener('load',replaceSrc); 

如果要与旧的IE浏览器兼容,请使用

  if(window.addEventListener){
window.addEventListener('load',replaceSrc,false);
} else if(window.attachEvent){
window.attachEvent('onload',replaceSrc);
}






,似乎您正在尝试更改由另一个来源服务器提供的iframe的src。由于同源政策,您无法执行此操作。请参见例如此相关问题:更改跨网域的iframe


I have HTML/CSS/JS page with CSS and JS functions (not created by myself) defined within the <head> tag. The page is displaying the title at the beginning and beneath there are four tabs defined by CSS style working dynamically using JS. Then I wanted to add my own JS function, which should be loading onload:

<script type="text/javascript"> 
    function replaceSrc()
    {
        document.getElementById("ytplayer").src = "blablabla";
    }
    window.onload = replaceSrc;
</script>

However, when running the page, all content produced by CSS/JS disappears (just the title of the page remains).

So my questions are:

  1. Can be the problem that there is already one JS function defined that is loading onload?
  2. If so, how to handle it?

I have already tried to put the function declaration into different places within HTML, removing from tag and putting into tag, but still does not work.

解决方案

When you (or somebody's else) use window.onload = someFunction, you remove all precedently attached load event handler.

You should use addEventListener :

window.addEventListener('load', replaceSrc);

If you want to be compatible with old IE browsers, use

if (window.addEventListener){
  window.addEventListener('load', replaceSrc, false);
} else if (window.attachEvent) {
  window.attachEvent('onload', replaceSrc);
}


EDIT : From your comment, it seems that you're trying to change the src of an iframe which is served by another server from another origin. You can't do this due to same origin policy. See for example this related question : Change src Iframe with cross-domain

这篇关于我的Javascript函数受已定义的另一个JS函数的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆