获取触发事件的元素的ID
时间:2020-03-05 18:48:55 来源:igfitidea点击:
有什么方法可以获取触发事件的元素的ID?
我在想类似的东西:
<html> <head> <script type="text/javascript" src="starterkit/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $("a").click(function () { var test = caller.id; alert(test.val()); }); }); </script> </head> <body> <form class="item" id="aaa"> <input class="title"></input> </form> <form class="item" id="bbb"> <input class="title"></input> </form> </body> </html>
当然,如果从第一种形式触发该事件,则vartest
应当包含id" aaa",如果从第二种形式触发该事件,则应包含id" bbb"。
解决方案
回答
我们可以使用(this)来引用触发该函数的对象。
例如,当我们位于回调函数(在jQuery的上下文中)内部时,"'this'"是一个DOM元素,例如,由click,each,bind等方法调用。
在这里我们可以了解更多信息:http://remysharp.com/2007/04/12/jquerys-this-demystified/
回答
在jQuery中,event.target
总是指触发事件的元素,其中'event'是传递给函数的参数。 http://api.jquery.com/category/events/event-object/
$(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); });
还要注意this'也可以使用,但是它不是jQuery对象,因此如果我们希望在其上使用jQuery函数,则必须将其称为
'$(this)'`,例如:
$(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); }); });
回答
供参考,试试这个!有用!
jQuery("classNameofDiv").click(function() { var contentPanelId = jQuery(this).attr("id"); alert(contentPanelId); });