Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - Dynamic URL based on date and time for Iframe?

I'm trying to create a dynamic iframe that loads a page that is named after the date in yyyy-mm-dd format with the addition of +AM and +PM added at the end. Example: https://example.com/display/stuff/2016-10-02+AM

This is what I have so far.. I'm not getting any syntax errors but it won't render.

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
    var today = new Date();
    var dd = today.getDate;
    var mm = today.getMonth;
    var yyyy = today.getFullYear;
    var h = h > 12 ? h - 12 + 'PM' : h + 'AM';
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var today = yyyy + '-' + mm + '-' + dd + '+' + h;
</script>
document.body.innerHTML = ('<iframe src="https://example.com/display/stuff/'today'/"'</iframe>')
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

<script type="text/javascript">
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    var tmpHour =  today.getHours();
    var h =tmpHour > 12 ?  tmpHour - 12 + 'PM' :  tmpHour + 'AM';
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var dateString = yyyy + '-' + mm + '-' + dd + '+' + h;

   var iframe = document.createElement('iframe');
   iframe.setAttribute('src', 'https://example.com/display/stuff/' + dateString);
   document.body.appendChild(iframe);
</script>

You had several syntax errors, and mostly you forgot to invoke the Date functions - you did not add ();

Also know that the month is always returnd -1 (it is from 0 to 11 instead of 1 to 12)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...