[英]How do I call a function that is defined inside of require() outside of the require()?
我正在使用ArcGIS API for Java 3.21。 我在require()內部有一個函數。 我希望在單擊按鈕時調用該函數,但是該按鈕位於require()之外。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//js.arcgis.com/3.7/js/esri/css/esri.css">
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 1;
padding: 1;
}
</style>
<script src="//js.arcgis.com/3.7/"></script>
<script>
var map;
require([
"esri/map",
"esri/geometry/Point",
"esri/symbols/SimpleMarkerSymbol",
"esri/graphic",
"esri/layers/GraphicsLayer",
"dojo/domReady!"
], function(
Map, Point, SimpleMarkerSymbol, Graphic, GraphicsLayer
) {
map = new Map("map", {
basemap: "gray",
center: [10,10],
zoom: 3
});
map.on("load", function() {
var graphicslayer = new GraphicsLayer();
map.addLayer(graphicslayer);
});
function hello(){
alert("hello,world!");
}
});
</script>
</head>
<body>
<button type="submit"class="searchButton"onclick="hello()">Search</button>
<div id="map"></div>
</body>
</html>
我無法在onclick =“ hello()”中調用hello(),因為hello()位於require()內部。
您好函數的作用域是require函數。 您希望將其范圍限定為全局對象,在您的情況下為窗口對象。 所以:
function hello(){
alert("hello,world!");
}
window.hello = hello;
或直接
window.hello = function(){
alert("hello,world!");
}
但是,您也可以直接在javascript中將hello函數綁定到對象的click事件; 您不必擴大功能范圍。 dojo庫中可能有這樣做的方法。 直接的JavaScript方式可能類似於
var myButton = document.querySelectorAll("button.searchButton")[0];
if (myButton) {
myButton.addEventListener("click", hello);
}
require({....})內的任何函數對onclick ='xxx('bbb')'不可見
您有2種選擇:
1)將此功能移到require({....})之外
2)如果函數必須在require({....})內部,則必須通過(如@Nicolas所說)將其作為全局函數
window.xxx = function(bbb){
alert(bbb);
}
您不能在require內部調用某個函數以供以后使用,因為hello函數位於匿名函數內部,而require函數只運行一次,並且無法恢復require函數內部的內容。
因此,如果您想在需要時致電hello,則hello必須位於require stament之外。
您還可以使用dojo模塊“ On”:
將此添加到您的需求init中:
require([...,"dojo/on",...], function(...,on,...) {
現在編寫事件處理程序(假設您向按鈕添加一個id):
<button type="submit" class="searchButton" id="searchButton">Search</button>
on(dojo.byId('searchButton'), 'click', function(evt) {
alert('hello');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.