Get ID of element that called a function

前端 未结 7 642
梦毁少年i
梦毁少年i 2020-12-07 20:02

How can I get the ID of an element that called a JS function?

body.jpg is an image of a dog as the user points his/her mouse around the screen at different

7条回答
  •  清歌不尽
    2020-12-07 20:29

    I know you don't want a jQuery solution but including javascript inside HTML is a big no no.

    I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).

    So in the interest of other people who may see this question, here is the jQuery solution:

    $(document).ready(function() {
      $('area').mouseover(function(event) {
        $('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
      });
    });
    

    The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.

    Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.

    Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.

提交回复
热议问题