迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中的事件目标

作者:迹忆客 最近更新:2023/03/10 浏览次数:

在本文中,我们将学习 JavaScript 源代码中的 event.target 属性以及该属性在 JavaScript 网页中的好处。

event.target 属性有助于查找用于触发事件的 HTML 元素的名称。例如,如果我们从一个 HTML 元素点击事件中调用一个函数,我们可以确定指定的元素名称来触发并调用一个函数。

为了获得该属性,我们调用 event.target 并将其存储在类似 let variable = event.target 的变量中。现在,我们可以使用该变量获得多个 event.target 属性。

它返回对发生事件的对象的引用。借助事件的 target 属性,我们可以执行以下任务。

现代网络浏览器完全支持这个 target 事件属性。

基本语法:

var property = event.target;
var elementName = property.tagName

在下面的示例中,我们将一起使用 event.target 对象和 tagName 属性来确定用于触发点击事件并调用声明的函数的元素名称。

例子:

<!DOCTYPE html>
<html>
   <body onclick="myFunction(event)">
      <h1 style="color:blueviolet">DelftStack Learning</h1>
      <h3>JavaScript Target event property</h3>
      <p>Click on button on this web page in this document to find out the element name which is used to triggered the event.</p>
      <button>Click here</button>
      <p id="myPara"></p>
      <script>
         function myFunction(event) {
             var myVariable = event.target; // get tagert event property
             document.getElementById("myPara").innerHTML = "Event triggered by a " + myVariable.tagName + " element";
         }
      </script>
   </body>
</html>

在上面的 HTML 网页源代码中,我们使用了 HTML 元素按钮来触发事件并调用 myFunction。在该函数中,我们必须获取一个事件作为参数,使用变量 myVariable,并使用该事件存储属性。

然后,我们简单地使用默认的 document.getElementById('myPara').innerHTML 将字符串文本分配给段落元素。我们已经在正文中创建了段落元素并分配了 ID myPara

我们将标签名称与 myVariable.tagName 连接起来,以在段落中显示元素名称。你可以将上述源代码保存在 HTML 扩展中,在浏览器中打开,然后查看结果。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便