更新div内容的问题

时间:2016-02-28 15:37:54

标签: javascript jquery

作为Javascript的新手,我发现这种语言并不容易。下面的代码在两个div之间淡出。在淡入淡出期间,我想改变每个div的内容。虽然我可以成功更新CSS参数,但我无法更新内容。也许有人可以提供帮助:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<html>

<head>
  <style type='text/css' media='screen, print'>
    #cycler {
      position: relative;
    }
    #cycler div {
      position: absolute;
      z-index: 1;
      background-color: white
    }
    #cycler div p {
      font-size: 60px;
      color: black;
      margin: 0;
    }
    #cycler div.active {
      z-index: 3
    }
    #cycler img {
      display: block
    }
  </style>
  <script type='text/javascript'>
    $(window).load(function() {
      setInterval('divCycler()', 3000);
    });

    function divCycler(e) {
      var $active = $('#cycler .active');
      var $next = ($active.next().length > 0) ? $active.next() : $('#cycler div:first');
      $next.css('z-index', 2);
      $active.fadeOut(1500, function() {
        $active.css('z-index', 1).show().removeClass('active');
        $active.innerHTML = "New HTML Text"; // This Line is not working !!!!!!!!!!!
        $active.css('background-color', 'red');
        $next.css('z-index', 3).addClass('active');
      });
    }
  </script>
</head>

<body>
  <div class='container'>
    <div id='cycler'>
      <div id='div1' class='active'>
        <p>Test Message 1</p>
      </div>
      <div id='div2'>
        <p>Test Message 2</p>
      </div>
    </div>
  </div>
</body>

</html>

我已经展示了包含所有Javascript的完整HTML页面;这没有其他代码。任何有关该问题的帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

$active.innerHTML = "New HTML Text"; // This Line is not working !!!!!!!!!!!

是因为$active是一个jQuery对象,而不是DOM元素,以解决您的问题:

$active[0].innerHTML = "New HTML Text";

或者,使用jQuery本身:

$active.html("New HTML Text");

答案 1 :(得分:0)

使用.html()代替innerHTML

        $active.html("New HTML Text"); // This Line is not working

jQuery Documentation: html()