从复合组件执行JavaScript [英] Execute JavaScript from a Composite Component
问题描述
早上好,我有一个困扰我几个小时的问题.非常简单.呈现复合组件时,我尝试调用/执行JavaScript.就像您可以使用html标签正文和onload一样.
Good day, I have a problem that has annoyed me for a couple of hours now. It's very straight forward. I try to invoke/execute a JavaScript when the composite component is rendered. Like what you can do with the html tag body and onload.
如何引用要执行的嵌入式JavaScript?
How can I reference the in-line JavaScript to be executed ?
<cc:implementation>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false" />
<div id="#{cc.clientId}" >
<div id="map_canvas" style="width: 850px; height: 350px; padding: 1px; border: darkblue" />
<script>init();</script>
<script type="text/javascript">
var map = null;
function init() {
var latlng = new google.maps.LatLng(51.5001524, -0.12623619);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</div>
</cc:implementation>
我已经尝试过this.init(),#{cc.clientId} .init(),但是在上下文中找不到JS.如果我从JSF/ajax组件执行它,则只需使用"init();"就可以正常工作.
I have tried with this.init() , #{cc.clientId}.init() .But the JS can't be found in the context. If I execute it from a JSF/ajax component it works fine with just "init();"
推荐答案
您正在调用init()
之前,该函数已定义.
You're calling init()
before the function has been definied.
将调用放在函数定义之后.
Put the call after the function definition.
<script type="text/javascript">
var map = null;
function init() {
var latlng = new google.maps.LatLng(51.5001524, -0.12623619);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
<script>init();</script>
或者只是摆脱函数调用,而直接执行它.在定义了<div id="map_canvas">
之后,它就可以执行了.
Or just get rid of the function call and just execute it directly. It'll just work as it's been executed after <div id="map_canvas">
has been definied.
<script type="text/javascript">
var map = null;
var latlng = new google.maps.LatLng(51.5001524, -0.12623619);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
</script>
不相关与具体问题:复合组件中还有另一个设计缺陷.在同一视图中,此组件不能重复使用一次.您最终将在HTML中使用多个<div id="map_canvas">
元素.在HTML中具有多个具有相同id
的元素是非法的.相应地修复它:
Unrelated to the concrete problem: you've another design flaw in your composite component. This component cannot be reused more than once in the same view. You would end up with multiple <div id="map_canvas">
elements in the HTML. Having multiple elements with the same id
in HTML is illegal. Fix it accordingly:
<div id="#{cc.clientId}_map_canvas" ...>
和
... document.getElementById("#{cc.clientId}_map_canvas") ...
这篇关于从复合组件执行JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!