Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

javascript - 获取触发事件的元素的ID(Getting the ID of the element that fired an event)

Is there any way to get the ID of the element that fires an event?

(有什么方法可以获取触发事件的元素的ID?)

I'm thinking something like:

(我在想类似的东西:)

<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>

Except of course that the var test should contain the id "aaa" , if the event is fired from the first form, and "bbb" , if the event is fired from the second form.

(当然,如果从第一种形式触发事件,则var test应包含id "aaa" ;如果从第二种形式触发事件,则应包含id "bbb" 。)

  ask by Joda translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function.

(在jQuery中, event.target始终指触发事件的元素,其中event是传递给函数的参数。)

http://api.jquery.com/category/events/event-object/

(http://api.jquery.com/category/events/event-object/)

$(document).ready(function() {
    $("a").click(function(event) {
        alert(event.target.id);
    });
});

Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this) , eg:

(还请注意, this也将起作用,但它不是jQuery对象,因此,如果您希望在其上使用jQuery函数,则必须将其称为$(this) ,例如:)

$(document).ready(function() {
    $("a").click(function(event) {
        // this.append wouldn't work
        $(this).append(" Clicked");
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...