onclick不能与其他JS文件一起使用

时间:2014-05-04 22:26:11

标签: javascript html

当onclick与Kill_Count不在同一个html文件中时会起作用,但当它们在一起时,只执行Kill_Count文件,按钮仍会显示,但是当你点击它时,没有任何反应......

Button.html:

<html>
<head>
    <script src="window.js"></script>
    <script src="Kill_Count.js"></script>
</head>
<body>
    <button type="button" id="Vegan Site">Vegan Site</button>
    <table>
      <tr>
        <td width="424.2">
      Some stuff about Animals.
        </td>

      <td>        
      <table cellpadding="0" cellspacing="0">   

        <tr>
        <td>Chickens</td>
        <td align="right">
        <span id="Kill_Count"></span>
        </td>
        </tr>

        <tr>
        <td>Pigs</td>
        <td align="right">
        <span id="Kill_Count2"></span>
        </td>
        </tr>

      </table>  
      </td>
      </tr>
    </table>  
</body>
</html>

window.js:

window.onload = function () {
    function myFunction() {
        window.open("http://www.abolitionistapproach.com/");
    }

    var Process = document.getElementById('Vegan Site');
    Process.onclick = myFunction;
}

Kill_Count.js

function Kill_Count(id)
{
  var animal = "Chickens";
  var totalDeaths = 49877536490;
  var deathsPerSecond = totalDeaths/365/24/60/60/4;
  var deaths = 0;
  var timer = 1;
  setInterval(function() {    
     deaths = deathsPerSecond*timer;     
     result = deaths.toFixed();
     document.getElementById(id).innerHTML = result;
     timer++;
  }, 250);
}

function Kill_Count2(id)
{
  var animal = "Pigs";
  var totalDeaths = 1375940758;
  var deathsPerSecond = totalDeaths/365/24/60/60/4;
  var deaths = 0;
  var timer = 1;
  setInterval(function() {    
     deaths = deathsPerSecond*timer;     
     result = deaths.toFixed();
     document.getElementById(id).innerHTML = result;
     timer++;
  }, 250);
}


window.onload = Kill_Count('Kill_Count');
window.onload = Kill_Count2('Kill_Count2');

1 个答案:

答案 0 :(得分:0)

在最后一行中,您将覆盖上一行。 window.onload只能有一个值,当你分配两次时,最后一次获胜。出于同样的原因,当您包含这两个文件时,将覆盖window.onload,并忽略对window.onload的window.js赋值。请注意,由于您没有在Kill_Count中返回一个函数,因此您实际上将undefined分配给window.onload,并且该函数在您分配时正确运行,而不是真正在加载时运行。基本上,没有任何事情发生在负载上。

要向window.onload添加多个侦听器,您需要使用window.addEventListener("load", someFunction, false)(和window.attachEvent("onload", someFunction);,如果您支持Internet Explorer 8及更低版本)。你可以多次调用它,所有的功能都会在加载时激活。