Getting an #id from jQuery's this

孤者浪人 提交于 2019-12-25 06:38:53

问题


How do I get the ID associated with the this keyword? I've tried several things from SO pages but here is where I've decided to open the question:

$('.anySelector').waypoint(function() {
    console.log(this); // entire selector's content
    var thisContent = this;
    console.log($(thisContent).attr('id')); // undefined
});

回答1:


If this really is a DOM Element (which is very probable using jQuery) it is as simple as just accessing the id property of the element.

jQuery( '.anySelector' ).waypoint( function() {
    console.log( this.id );
} );

If you really need to go the jQuery way (i.e. using the attr method) you must turn this into a jQuery object first:

jQuery( '.anySelector' ).waypoint( function() {
    console.log( jQuery( this ).attr( 'id' ) );
} );


来源:https://stackoverflow.com/questions/22665134/getting-an-id-from-jquerys-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!