简体   繁体   English

触发事件时调用 cesium.js 中的函数

[英]Calling a function in cesium.js when a event is trigerred

I have a div created as below我创建了一个 div,如下所示

<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>Loading...</h1></div>
<div id="toolbar"><input type="search" id="search" placeholder="Search by layout name" onkeydown="search()"/></div>

So when enter button is pressed in search box, it should call the function " Search ".所以当在搜索框中按下输入按钮时,它应该调用函数“搜索”。

<script id="cesium_sandcastle_script">
function startup(Cesium) {
'use strict';
 var west = 68.0;
 var south = 7.0;
 var east = 89.0;
 var north = 35.0;
 var rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);

 Cesium.Camera.DEFAULT_VIEW_FACTOR = 0.5;
 Cesium.Camera.DEFAULT_VIEW_RECTANGLE = rectangle;
 var viewer = new Cesium.Viewer('cesiumContainer', {
   timeline: false,
   animation : false,
   vrButton : true,
   selectionIndicator : false
 });


   function search() {
      alert("success");
   }
 }

When i run this it is raising an error " search is not a function ".当我运行它时,它会引发错误“搜索不是功能”。 Where am i wrong?我哪里错了?

The problem is that Cesium Sandcastle wraps your code in a startup function, as you can see in the first line of JavaScript in your question above, and this shields local declarations from the global scope.问题在于 Cesium Sandcastle 将您的代码包装在startup函数中,正如您在上述问题的第一行 JavaScript 中所见,这将局部声明与全局范围屏蔽了。 So there's no window.search function to bind to.因此没有要绑定到的window.search函数。 But binding global functions like this isn't best practice these days.但如今,像这样绑定全局函数并不是最佳实践。

Give this a try instead: remove the onkeydown="search()" attribute from your HTML code above, and instead subscribe to the event in JavaScript like so:试试这个:从上面的 HTML 代码中删除onkeydown="search()"属性,而是像这样在 JavaScript 中订阅事件:

function search() {
    console.log('testing search...');
}

document.getElementById('search').addEventListener('keypress', search, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM