简体   繁体   中英

Javascript function in wordpress page won't work

I have made a script that takes a year as parameter and then prints out the difference from current year in words. The word part I haven't done myself, I found a bit of code that worked which I used.

When I try the code in for example jsfiddle and call it with

document.getElementById("demo").innerHTML = yearDiff(1968);

and it works when I use this HTML code.

<p id="demo"></p>

But when I try to run it within a Wordpress page for testing it doesn't work. Here is what I insert to the page.

<script type="text/javascript">
    var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','
    var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];

    function yearDiff(startYear) {
        var currentDate = new Date();
        var currentYear = currentDate.getFullYear();     
        num = currentYear - startYear;

        n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
        if (!n) return;
        var str = '';
        str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) : '';
        return str;
    } 
    yearDiff(1975);
</script>

What have I done wrong?

In your last example you're just calling the function ( yearDiff(1975); ) but doing nothing with the return value..

Are you missing some code, or is just this your problem?

EDIT

I was looking again at your code and you have this: var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','

You didn't finish your array.. You surely have an error in your javascript console yelling some unexpected token or something like that....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM