写法一:推荐方法。用object.addEventListener("click", myScript)
具体写法如下:
<!DOCTYPE html>
<html>
<body>
<p>本例使用 addEventListener() 方法将 "click" 事件附加到 p 元素。</p>
<p id="demo">点击我.</p>
<script>
document.getElementById("demo").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "YOU CLICKED ME!";
}
</script>
</body>
</html>
写法二 :
<!DOCTYPE html>
<html>
<body>
<h1>onclick 事件</h1>
<p>onclick 事件用于在单击元素时触发函数。</p>
<p>单击按钮触发一个函数,该函数将在 id="demo" 的 p 元素中输出 "Hello World"。</p>
<button onclick="myFunction()">点击我</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
写法二,如果你使用Dojo框架,那是不起作用的,用到Dojo框架了,还是第一种写法最好用。它能起作用,能干活,而写法二不起作用。
下面是从例子种摘录的几个实际的代码片段供参考。
// Set up a click event handler and retrieve the screen point
view.on("click", function(event) {
// the hitTest() checks to see if any graphics in the view
// intersect the given screen x, y coordinates
view.hitTest(event)
.then(getGraphics);
});
view.on("click", function(event) {
// you must overwrite default click-for-popup
// behavior to display your own popup
view.popup.autoOpenEnabled = false;
// Get the coordinates of the click on the view
let lat = Math.round(event.mapPoint.latitude * 1000) / 1000;
let lon = Math.round(event.mapPoint.longitude * 1000) / 1000;
view.popup.open({
// Set the popup's title to the coordinates of the location
title: "Reverse geocode: [" + lon + ", " + lat + "]",
location: event.mapPoint // Set the location of the popup to the clicked location
content: "This is a point of interest" // content displayed in the popup
});
});
view.on("pointer-move", (event) => {
// only include graphics from hurricanesLayer in the hitTest
const opts = {
include: hurricanesLayer
}
view.hitTest(event, opts).then((response) => {
// check if a feature is returned from the hurricanesLayer
if (response.results.length) {
const graphic = response.results[0].graphic;
// do something with the graphic
}
});
});
该函数的参考文档位于:
JavaScript添加事件处理函数的两种方法

本文介绍了JavaScript中为元素添加事件处理函数的两种方法,推荐使用`addEventListener`。写法二在Dojo框架中可能不起作用,而写法一更为通用且适用。文章提供了一些实际代码片段,并引用了MDN的`addEventListener`文档作为参考。

被折叠的 条评论
为什么被折叠?



