get jquery `$(this)` id

后端 未结 2 1432
不思量自难忘°
不思量自难忘° 2020-12-29 20:46

How can I get the id of the element that triggered the jQuery .change() function? The function itself works properly, but I need a specific action

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-29 20:59

    this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

    $("select").change(function() {    
        alert("Changed: " + this.id);
    }
    

    Live example

    You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

    $("#container").change(function(event) {
        alert("Field " + event.target.id + " changed");
    });
    

    Live example

    (jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

提交回复
热议问题