0

I have this file: a.js

export function work(){
    // do stuff
}

And this jsp file:

...
<script type="text/javascript" src='<c:url value="/javascripts/a.js"/>'></script>
...

How do I call the function "work" from my jsp file? It always says "work is not defined"

Attempted (deeper in the jsp):

...
    <th><a href="#" onclick="return work();" > Work # </a></th>
...
bharal
  • 15,461
  • 36
  • 117
  • 195
  • Have you tried `"return window.work();"`? Since the script is in the HEAD, the DOM may not be initialized yet. You may need to listen for `DOMContentLoaded`. – Mr. Polywhirl Jan 21 '20 at 14:15
  • `href="#"` — if you're linking to the top of the page then you probably shouldn't be using a link and should be using a ` – Quentin Jan 21 '20 at 14:16
  • This might help if you still want to use modules. https://stackoverflow.com/questions/44590393/es6-modules-undefined-onclick-function-after-impor – Yury Tarabanko Jan 21 '20 at 14:17

2 Answers2

1

export is only supported in ES6 modules, and you aren't loading the JS file as a module.

Remove the export keyword.

(If you were loading it as a module <script src="..." type="module"></script> then work wouldn't be a global so you couldn't call it from an on* attribute anyway).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

you don't need to export the function if you linking the file then remove the return and the href and replce the with a button it's better:

<th><<button onclick="work();" > Work # </button></th>
Aziz.G
  • 3,599
  • 2
  • 17
  • 35