如何仅获取JQuery中的clicked元素 [英] How to get only the clicked element in JQuery

查看:93
本文介绍了如何仅获取JQuery中的clicked元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅获取JQuery中的单击元素

How to get only the clicked element in JQuery

假设以下

<html>
  <body>
    <div>
      <h1>headding</h1>
    </div>
    <a>link</a>
  </body>
</html>

$("*").click(function(e){
   e.preventDefault();
   alert($(this)[0].tagName);
});

我需要在单击h1时警报显示h1 并单击a时,警报将显示a等.

I need when click on h1 the alert show h1 and when click on a the alert show a etc.

问题是当我单击任何元素时,代码make循环将显示被单击元素的所有父元素的名称.但我只需要第一个单击的元素.任何帮助

The problem is when i click on any element the code make loop to show name of all parents element of the clicked element. but i need only the first clicked element. any help

推荐答案

使用 stopPropagation()因此活动不会冒泡

$("*").click(function(e){
   e.preventDefault();
   e.stopPropagation();
   alert($(this)[0].tagName);
});

FIDDLE

这篇关于如何仅获取JQuery中的clicked元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆