2017-08-14 107 views
-2

我使用ArcGIS API for Javascript 3.21。我在require()中有一個函數。我希望在單擊按鈕時調用該函數,但該按鈕不在require()中。如何在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> 

因爲hello()在require()中,所以我無法在onclick =「hello()」中調用hello()。

+0

https://en.wikipedia.org/wiki/Unobtrusive_JavaScript – zzzzBov

回答

1

您的hello函數的作用域被定義爲require函數。您想將其範圍限定爲全局對象,即您的案例中的窗口對象。因此,要麼:

function hello(){ 
    alert("hello,world!"); 
} 
window.hello = hello; 

或直接

window.hello = function(){ 
    alert("hello,world!"); 
} 

但你也可以在你的Hello功能綁定到你的直接對象的JavaScript中的單擊事件;你不必擴大你的功能範圍。道場圖書館可能會這樣做。一個直接的JavaScript的方式可能是像

var myButton = document.querySelectorAll("button.searchButton")[0]; 
if (myButton) { 
    myButton.addEventListener("click", hello); 
} 
+0

哇哦!我沒有意識到這很簡單。 – cccompro

0

你不能叫內需要的功能後使用,因爲你好函數是一個匿名函數,它需要的功能運行一次裏面,這是不可能恢復需要什麼功能。

所以,如果你想在你需要的時候打電話給你打招呼,

0

你也可以使用Dojo模塊「開」:

添加到您需要的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'); 
}); 
相關問題