使用jquery替换日期格式

时间:2017-07-26 19:13:20

标签: jquery

基本上,我想将8月更换为AUG,7月更换为JUL,6月更换为JUN ...... 这是我下面的代码,我尝试使用Jquery,它确实无法工作,有人可以帮助我吗?

<!DOCTYPE html>
    <html>
        <body>
            <p class="post-date">August</p>
            <p class="post-date">July</p>
            <p class="post-date">June</p>
            <script>
                var thisDate = $('.post-date');
                var dateformat = $('.post-date').text();
                switch (dateformat)
                {
                   case 'August': thisDate.text("AUG");
                   break;

                   case 'July': thisDate.text("JUL");
                   break;

                   case 'June': thisDate.text("JUN");
                   break;

                   default:  thisDate.text("JULY");
                }
            </script>
        </body>
    </html>

1 个答案:

答案 0 :(得分:-1)

您需要迭代每个post-date并分别处理每个实例。

您可以使用对象来简化此

var shortMonths = {
  August: "AUG",
  July: "JUL",
  June: "JUN"
}

$('.post-date').text(function(_, month) {
  return shortMonths[month] || "JUL"
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="post-date">August</p>
<p class="post-date">July</p>
<p class="post-date">June</p>