问题
I want to execute JavaScript in my application which is written with GWT. This is the code that works in a regular HTML:
<html>
<head>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script src="jquery.js"></script>
<script src="jquery.roundabout.js"></script>
<script>
$(document).ready(function() {
$('ul').roundabout();
});
</script>
</body>
</html>
(Assume jquery.js and jquery.roundabout.js are in the same folder.)
I have a somePresenter (with someView.java and someView.ui.xml) and I want the above code to work in the someView.ui.xml.
I copy pasted the above code to the XML (except for <html> tag I have <g:HTMLPanel> tag)
but the JavaScript doesn't seem to be executed (all I see is the list as it should be before the script).
How can I make it work?
Related question: can I some how use GQuery for this (something like: GQuery.$().getScript(jquery.roundabout.js) to load external js script)?
Thanks in advance
回答1:
You can't put a <script> in UiBinder and expect to see it loaded and executed for the same reasons you cannot put a <script> in a innerHTML in JS with the same expactations (simply because HTMLPanel and UiBinder will use innerHTML under-the-hood).
If you need to load scripts dynamically, have a look at the ScriptInjector:
ScriptInjector.fromUrl(GWT.getModuleBaseURL() + 'jquery.js').inject();
I suppose GQuery uses ScriptInjector or works similarly.
回答2:
I eventually managed to do this by putting the
<script src="jquery.js"></script>
<script src="jquery.roundabout.js"></script>
in the project.html
and then executing the relevant JavaScript with JSNI call when the relevant page loaded (my presenter).
来源:https://stackoverflow.com/questions/10178034/how-to-use-javascript-with-gwt-uibinder