javascript OnClick 事件 - 检查哪个是发件人

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10298629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:22:26  来源:igfitidea点击:

OnClick event - check which is the sender

javascriptjquery

提问by petko_stankoski

Is there a way to call one event every time when something on my page is clicked (whether a control or something else), and then in that function to check which is the sender?

有没有办法在每次单击我页面上的某些内容(无论是控件还是其他内容)时调用一个事件,然后在该函数中检查哪个是发件人?

回答by Mathletics

like this?

像这样?

$(document).click(function(e) {
  console.log(e.target);
});

This will capture all clicks in the document and log the node on which the event started. It's a bit of a sledgehammer approach, but without understanding the problem it's the best I can do.

这将捕获文档中的所有点击并记录事件开始的节点。这有点像大锤的方法,但在不了解问题的情况下,这是我能做的最好的事情。

回答by asawyer

Well you could do something like:

那么你可以做这样的事情:

$(function(){
    $('*').click(function(){
        var $sender = $(window.event.target);
    });
});

However, you'll have all sorts of propegation issues I'd imagine, plus I dont know if all dom elements respond to the .click()event.

但是,您会遇到我想象中的各种传播问题,而且我不知道是否所有 dom 元素都响应该.click()事件。

It'd be better to tag all the items you want to be clickable with a class name, so it becomes:

最好用一个类名标记你想要点击的所有项目,所以它变成:

$(function(){
    $('.clickable').click(function(){
        var $sender = $(window.event.target);
    });
});

What exactly are you trying to accomplish?

你到底想完成什么?

回答by Shyju

You can identify which item being clicked like this. The below script will take care of all a tag in your page.

您可以像这样识别被点击的项目。下面的脚本将处理您页面中的所有标签。

$(function(){
    $("a").click(function(e){
    // e.preventDefault(); prevent default behaviour if needed
     alert("Invoked from "+$(this).attr("id"));   
    });
});?

Working sample : http://jsfiddle.net/yBfUq/2/

工作示例:http: //jsfiddle.net/yBfUq/2/

回答by Matthew Riches

There is indeed, although I cannot think of any reason you would want to do this?

确实有,虽然我想不出你想要这样做的任何理由?

http://jsfiddle.net/WkNPg/

http://jsfiddle.net/WkNPg/

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

});

This will alert the id, but you can make it so anything you want based on the "sender".

这将提醒 id,但您可以根据“发件人”设置任何您想要的内容。