使用 jQuery 获取有关事件源的信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1375280/
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-08-26 11:18:32  来源:igfitidea点击:

Get information about the source of an event with jQuery

jqueryjquery-events

提问by Zian Choy

A function is bound to an event for many objects. One of those objects fires the event and jQuery kicks in. How do I find out who fired the event inside the JavaScript function?

一个函数绑定到许多对象的一个​​事件。其中一个对象触发事件,jQuery 启动。如何找出谁在 JavaScript 函数中触发了事件?

I've tried using function [name](event){}and poking at event but I get "'data' is null or not an object".

我试过使用function [name](event){}和戳事件,但我得到“'数据'为空或不是对象”。

Here's my code right now:

这是我现在的代码:

<script type="text/javascript">
    $(document).ready(function() {
    $('.opening').bind("click", function(event) {
         //code to populate event.data since right now, the tags don't hold the info...they will eventually with an XHTML custom namespace
            event.data.building = "Student Center";
            event.data.room = "Pacific Ballroom A";
            event.data.s_time = "9/15/2009 8:00";
            event.data.e_time = "9/15/2009 10:00";

            indicatePreferenceByClick(event);
        });
    function indicatePreferenceByClick(event) {
        alert("I got clicked and all I got was this alert box.");
        $("#left").load("../ReserveSpace/PreferenceByClick", { building: event.data.building, room: event.data.room, s_time: event.data.s_time, e_time: event.data.e_time});
    };
</script>

回答by user7488658

Using targetyou can access the control that has caused the current execution/ event. Like this:

使用target您可以访问导致当前执行/事件的控件。像这样:

$(event.target)

回答by Parikshit Bhagawati

when you attach the event to multiple objects the best way to identify which of the elements fired the event is using the thiskeyword. Example -

当您将事件附加到多个对象时,识别触发事件的元素的最佳方法是使用this关键字。例子 -

$('.opening').bind("click", function(event) {

     var current = $(this); // will give you who fired the event.

     //code to populate event.data since right now, the tags don't hold the info...they will eventually with an XHTML custom namespace
        event.data.building = "Student Center";
        event.data.room = "Pacific Ballroom A";
        event.data.s_time = "9/15/2009 8:00";
        event.data.e_time = "9/15/2009 10:00";

        indicatePreferenceByClick(event);
    });

let me know if this helps.

如果这有帮助,请告诉我。

回答by Sandip - Full Stack Developer

You can use the thisin Jquery function, it will give you the item which has injected event.

你可以在 Jquery 函数中使用this,它会给你注入事件的项目。

<script type="text/javascript">
$(document).ready(function() {
    $('.opening').bind("click", function(event) {
       console.log($(this));
    });
});    
</script>

回答by Sandip - Full Stack Developer

event.currentTargetmight be what you're looking for.

event.currentTarget可能就是你要找的。

If you're asking about event sourceas in Javawhere targetis the object that caused the event to be fired and sourceis the object to which the event handler was attached to, then this might be what you're looking for:

如果您问的是导致事件被触发的对象event sourceJava哪里target以及source事件处理程序附加到的对象,那么这可能就是您要查找的内容:

Within the eventobject which is passed to a handler when an event is fired, there are two objects include i.e. targetand currentTarget.

event触发事件时传递给处理程序的对象中,有两个对象,包括 ietargetcurrentTarget

  • targetis the object that caused the event to be fired
  • currentTargetis the object where the handler was attached to
  • target是导致事件被触发的对象
  • currentTarget是处理程序附加到的对象

To show it in your code:

要在您的代码中显示它:

<script type="text/javascript">
  $(document).ready(function() {
    $('.opening').bind("click", function(event) {
      // ...your code
      indicatePreferenceByClick(event, event.currentTarget);
    });
    function indicatePreferenceByClick(event, eventSource) {
      alert("I got the event source.");
      console.log(eventSource);
      // ...your code
    }
  });
</script>

For more Event.currentTarget

欲了解更多Event.currentTarget

Hope it helps :)

希望能帮助到你 :)

回答by Justin Russell

Here is a working example of a complete page. The caller is logged to the console in the line console.log($caller.prop("id"));:

这是一个完整页面的工作示例。调用者记录到控制台中的行console.log($caller.prop("id"));

<!DOCTYPE html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Untitled 1</title>
    <script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function() {
                    $('.opening').on("click", {building:"Student Center", room:"Pacific Ballroom A", s_time:"9/15/2009 8:00", e_time:"9/15/2009 10:00"}, function(event) {
                        indicatePreferenceByClick(event);
                    });

                    function indicatePreferenceByClick(event) {
                        alert("I got clicked and all I got was this alert box.");
                        var $caller = $(event.target);
                        console.log($caller.prop("id"));
                        var building = event.data.building;
                        var room = event.data.room;
                        var s_time = event.data.s_time;
                        var e_time = event.data.e_time;
                    };
        });
    </script>
</head>

<body>
<div style="padding:10px"><button type="button" id="button1" class="opening">button1</button></div>
<div style="padding:10px"><button type="button" id="button2" class="opening">button2</button></div>
</body>

</html>

回答by hightempo

You don't need jQuery at all to get the target of an event. It's always available as the currentTarget property of the event. You can use jQuery to set up the event handler, of course, but getting the target is easily done without using that library. For example:

您根本不需要 jQuery 来获取事件的目标。它始终可用作事件的 currentTarget 属性。当然,您可以使用 jQuery 来设置事件处理程序,但无需使用该库即可轻松获取目标。例如:

    <!DOCTYPE html>
    <html>
        <head>
            <script type="text/javascript" src="jquery.js"></script>
        </head>
        <body>

            <button type="button" id="button1" class="opening">button1</button>
            <button type="button" id="button2" class="opening">button2</button>

            <script type="text/javascript">
                $(document).ready(function() {
                    $('.opening').bind("click", function(event) {
                        indicatePreferenceByClick(event);
                    });
                });

                function indicatePreferenceByClick(event) {
                    console.log('target', event.currentTarget);
                }
            </script>

        </body>
    </html>

As for dealing with 'null' when trying to access event.data, that makes perfect sense because 'data' is not a property of a click event.

至于在尝试访问 event.data 时处理 'null',这是完全合理的,因为 'data' 不是点击事件的属性。

    $(document).ready(function() {
        $('.opening').bind("click", function(event) {
          // event.data is null so you can't add properties to it
            event.data.building = "Student Center";  // <- this will fail
            indicatePreferenceByClick(event);
        });
    });

You can either add another property to the data object like so:

您可以向数据对象添加另一个属性,如下所示:

$(document).ready(function() {
        $('.opening').bind("click", function(event) {
          event.data = {};
            event.data.building = "Student Center";
            indicatePreferenceByClick(event);
        });
    });

Or, you can pass another variable to your function:

或者,您可以将另一个变量传递给您的函数:

$(document).ready(function() {
        $('.opening').bind("click", function(event) {
          var data = {};
            data.building = "Student Center";
            indicatePreferenceByClick(event, data);
        });
    });