获取最后单击项目ID [英] Get last clicked item id

查看:142
本文介绍了获取最后单击项目ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的功能:

$(document).ready(function () {
          $("*").click(function () {             
              alert($(this).attr('id').toString());                
        });
    });

和上页我有这样的事情:

And on Page i have something like this:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script language="javascript" src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<div id="div1">Some stuff
    <div id="div2">Some other stuff
    <asp:Button ID="Button1" runat="server" Text="Button" />        
        <div id="div3">More stuff
        <asp:Button ID="Button2" runat="server" Text="Button" />        
        </div>
    </div>        
</div>   

如果我点击的东西它工作正常,但它提醒了我三次(或更多)。
例如:
我点击按钮2。 Alertbox出现与button2.id,然后用div3.id,div2.id等,这表明我所有的ID的那个按钮之下。
如果我尝试这个ID存储变量:

If i click something it works fine, but it alerts me three times(or more). For example: I click button2. Alertbox appears with button2.id, then with div3.id, div2.id etc. It shows me all id's under that button. If i try to store this id to variable like this:

     var storedId = $(this).attr('id').toString();

它存储了最后one.That意味着我得到Form1的ID。

it stores the last one.That means i get the id of form1.

我怎样才能获得第一个ID?点击按钮或点击标签或者其他,我有我的网页上的ID。

How can i get the first id? The id of clicked button or clicked label or whatever i have on my page.

推荐答案

您需要停止事件传播了DOM树,以便父项看不到相同的事件。在jQuery中,你可以做到这一点与 e.stopPropagation()

You need to stop event propagation up the DOM tree so parent items don't see the same event. In jQuery, you can do that with e.stopPropagation():

$("*").click(function(e) {
    alert($(this).attr('id').toString());                
    e.stopPropagation();
});

仅供参考,这是做一个非常低效的方式。

FYI, this is a really inefficient way to do this. You would do it better like this with a single event handler that takes advantage of event bubbling and catches the bubbled click events at the document and examines them in just this one place:

$(document).click(function(e) {
    alert(e.target.id);                
});

这篇关于获取最后单击项目ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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