JS 为某个元素添加事件处理函数的写法

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

写法一:推荐方法。用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
    }
  });
});

该函数的参考文档位于:

EventTarget.addEventListener() - Web APIs | MDNThe EventTarget method addEventListener() sets up a function that will be called whenever the specified event is delivered to the target.https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值