一个函数绑定到许多对象的事件.其中一个对象触发事件,jQuery开始.我如何知道谁在
JavaScript函数中触发了事件?
我尝试使用函数[name](event){}并且在事件上戳,但是我得到“’data’为null或不是一个对象”.
这是我现在的代码:
<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>
解决方法
这是一个完整页面的工作示例.调用者在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>