元素加载时执行javascript函数

时间:2012-11-25 17:22:30

标签: javascript html

当从AJAX出现HTML元素时,如何执行javascript函数。这是我的想法,但它没有执行闪烁:

    <!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Node JS</title>
    <style type="text/css">
      html , body {
        font: normal 0.9em arial , helvetica;
      }
    </style>
    <script src="http://0.0.0.0:3000/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">


    var a=0;
    function blinkColor()
    {
      document.getElementById("red").style.background="red"
      setTimeout("setblinkColor()",500)
    }

    function setblinkColor()
    {
      a++;
      if (a<4){
      document.getElementById("red").style.background=""
      setTimeout("blinkColor()",500)
      }
      else{
      document.getElementById("red").style.background=""
      }
    }



     $(document).ready(function() {
      var socket = io.connect('http://0.0.0.0:3000');
      var out = "";
      socket.on('populate', function(data) {
        $.each(data, function(i, obj) {
    if(obj['Ping'] == "FALSE"){
          out += "<li id='red'><font color='red'>"+obj.Vardas+" is down..."+obj.Data+"</font></li>";
    }
    else{
          out += "<li><font color='green'>"+obj.Vardas+" is up......."+obj.Data+"</font></li>"; 
    }
        });
    $('#database').html(out);
      });
    });
    </script>
  </head>
  <body onload = "blinkColor()">
  <div style="float:right; overflow:scroll; height: 400px; width: 30%">
    <ul id ='database'></ul>
  </div>
  </body>
</html> 

在socket中的loads数组中,获取值并生成html列表对象。列表生成,但我希望当元素出现时它会闪烁几秒钟。我需要为此调用blinColor()函数。

我添加了test.html以使用getElementsByClass调用元素但它不起作用......似乎很简单:

<html>
<head>
<script>
    var a=0;
    function blinkColor()
    {
      document.getElementsByClass('blink').style.background="red"
      setTimeout("setblinkColor()",500)
    }

    function setblinkColor()
    {
      a++;
      if (a<4){
      document.getElementsByClass('blink').style.background=""
      setTimeout("blinkColor()",500)
      }
      else{
      document.getElementsByClass('blink').style.background=""
      }
    }
</script>
</head>

<body onload="blinkColor()">
<h1 class="blink">Hello World!</h1>
<p class="blink">Hello World!</p>
</body>

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

  • getElementsByClass应为getElementsByClassName
  • 背景应为backgroundColor

示例代码:

var blinks=document.getElementsByClassName('blink');
for (var i=0,blinksCount=blinks.length;i<blinksCount;i++) {
    blinks[i].style.backgroundColor="red";
}