javascript - HTML5如何获取被点击对象的id?

标签 javascript html event-handling

我有一个这样的 Canvas 列表:

<div id="lists" style="position:absolute">
        <ul>
            <li>
                <canvas id="product1" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product2" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product3" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product4" class="product" width="1200" height="360"></canvas>
            </li>
            <li>
                <canvas id="product5" class="product" width="1200" height="360"></canvas>
            </li>
        </ul>
    </div>

我想为所有五个 Canvas 编写一个事件监听器:

$(".product").mousedown(function(e) {

}

我想知道用户在事件处理程序中单击了哪个 Canvas 。有办法知道吗?如果我为五个 Canvas 编写五个事件处理程序,代码将变得太难看。

最佳答案

答案就在事件对象和调用它的上下文中,它们是用回调函数解析的。您可以查看 $(this) 或 http://api.jquery.com/event.target/ .

$(".product").mousedown(function(e) {
    alert($(this).attr('id'));
});

会给你ID

关于javascript - HTML5如何获取被点击对象的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20318112/

相关文章:

javascript - 如何将 SortableJS 位置保存到对象中?

javascript - CSS/Javascript 图片转场

javascript - 在php foreach中使用javascript更改html div的值

c# - 如何在 Windows 应用程序中处理 Ctrl + Break 或 Ctrl + Pause

javascript - 如何访问 Microsoft Bot Framework 上的用户数据?

javascript - 如果我想要 "$$$"(两美元)作为 Java-/coffescript- 中的替换字符串,为什么我需要 "$$"(三美元)

javascript - 测试类无法读取consul配置

javascript - 具有 ID 的 DOM 树元素是否成为全局属性?

iphone - 如何通过单击按钮更改 UITableView 的内容?

C# 如何创建一个发布事件和订阅类的单例?