【问题标题】:displaying the ELEMENT NAME that triggered mouse event in javascript在 javascript 中显示触发鼠标事件的元素名称
【发布时间】:2014-10-18 16:34:31
【问题描述】:

我正在尝试让警报框显示元素名称(这里是 html)(显然没有硬编码)触发事件 onclick 并按下 ctrl。

<!DOCTYPE html>
<html onclick="alertD(event)">
<head>
<title>
</title>
</head>
<body>

<!--<p>click anywhere on the page to display alert dialog</p>-->



<script type="text/javascript">

function alertD(event) 
{
    if (event.shiftKey) 
    {
        alert(event);
    } 
    else if(event.ctrlKey) 
    {
        alert("html"); //-- this is where it would say something like alert(document.element)???
    }
    else
    {
        alert();
    }
}

【问题讨论】:

  • 看event.target-Event Target
  • @George 这不是重复的。那是指在询问如何获取目标元素的同时查看对象的构造函数。

标签: javascript event-handling ctrl


【解决方案1】:

您可以使用事件的target 属性来获取元素。然后使用元素的tagName 属性获取该元素的名称。

function alertD(event) 
{
    if (event.shiftKey) 
    {
        alert(event);
    } 
    else if(event.ctrlKey) 
    {
        alert(event.target.tagName); // <-- tag name
    }
    else
    {
        alert();
    }
}

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多