根据一天中的时间更改消息?

时间:2012-11-10 19:16:01

标签: jquery

我正在尝试根据一天中的时间更改消息。

我已将我在ST2中看到的内容粘贴到JSFiddle

这是:

<div class="container">
    <div id="time">
        <p id="time">Good morning.</p>
    </div>

<div>
    <p>I used to work in the marketing industry.<br>Now I'm a Web Designer and Developer.<br> I like to keep things simple.</p>
</div>​

Jquery的:

<script type="text/javascript">
 $(document).ready(function()
    {
      var now = new Date();
      var hours = now.getHours();
      var msg;
      if(hours<12)
           msg = "Good Morning";
      else if(hours<18)
           msg = "Good Afternoon";
      else
          msg = "Good Evening";
      return(msg);
    });
});
</script>​

当涉及到jquery时,我是一个完整的菜鸟,所以要温柔。

HTML:

<!DOCTYPE html>
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

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

  <script type="text/javascript">
      $(document).ready(function() {
      var now = new Date();
      var hours = now.getHours();
      var msg;
      if (hours < 12) msg = "Good Morning";
      else if (hours < 18) msg = "Good Afternoon";
      else msg = "Good Evening";
      $('#time p').text(msg);
    });
});
</script>

</head>

<body>

<div class="container">
    <div id="time">
        <p>Good morning.</p>
    </div>

<div>
    <p>I used to work in the marketing industry.<br>Now I'm a Web Designer and Developer.<br> I like to keep things simple.</p>
</div>​
</div>

</body>

2 个答案:

答案 0 :(得分:2)

只需将return msg更改为$('#time p').text(msg);

即可

DEMO:http://jsfiddle.net/EVCMm/10/

这使用jQuery text()方法替换在p

中查找ID=time标记的文字

API参考:http://api.jquery.com/text/

答案 1 :(得分:-4)

$('#time').html('<p>'+msg+'</p>');